Press "Enter" to skip to content

laravel的数据模型关联时的注意

语法格式:

在模型中:

1对1 hasOne(‘类’,’外键’,’主键’)

1对多 hasMany(‘类’,’外键’,’主键’)

反向关联使用belongTo(‘类’,’外键’,’主键’)

反向关联如商品和类型的关系 手机号和玩家的关系等

注意: 定义的格式如:

public function mytype()
{
return $this->belongsTo('App\Models\goods\GoodsType', 'type' , 'id');
}

方法名为后续结果集中的类型名,驼峰命名无效

对于分页paginate 对象 需要对attribute进行处理 如:

$mData = self::paginate($limit);
foreach ($mData as $item) {
    $item->attributes['goodtype'] = $item->mytype->name;
    $item->attributes['brand'] = $item->mybrand->name;
    $item->attributes['card'] = $item->mycard->name;
    $item->attributes['rarity'] = $item->myrarity->name;
}

方法名最好不要与 新的属性名相同,name字段特例

发表评论