Laravel属于即使使用特定的FK也不工作
问题描述:
我使用Laravel 5.3。Laravel属于即使使用特定的FK也不工作
我有2级表和2款(广告和类别):
Model ad :
----------------
class Ad extends Model
{
protected $table = 'ads';
protected $primaryKey = 'ad_id';
public function category()
{
return $this->belongsTo(Category::class, 'cat_id', 'cat_id');
}
}
而且
Model category :
-----------------
class Category extends Model
{
protected $table = 'categories';
protected $primaryKey = 'cat_id';
public function ads()
{
return $this->hasMany(Ad::class);
}
}
和我的数据库结构为:
ads:
ad_id -
ad_name
ad_status
cat_id
categoriess:
cat_id -
cat_name
我真的不知道为什么,但我无法得到使用此(在我的存储库)之间的关系:
return $this->model
->select('ad_id', 'ad_name')
->where('ad_status', '=', 1)
->with('category');
查询很好,我得到了ad
信息,但是关系是空的。我检查了两个表中存在的cat_id
。
我错过了什么吗?
答
您需要cat_id
键添加到select()
,使其工作:
return $this->model
->select('ad_id', 'ad_name', 'cat_id')
->where('ad_status', 1)
->with('category')
->get();
如果你不加这个关键,关系将永远null
。此外,请使用get()
来获取数据。
哦哇!谢谢你的男人!我没有想到这个......我猜想我在文档中错过了这个。 –
你不会在文档中找到它。很高兴帮助。 ) –
@VincentDecaux你也可以使用'$ this-> model-> with()' – xhulio