Laravel雄辩with()->返回null [英] Laravel Eloquent with()-> returning null
问题描述
我正在尝试使用Eloquent来获取具有映射到brands
表的brand_id
列的特定产品,而brand
数组又变空了.
I am trying to use Eloquent to get a specific product that has a brand_id
column that maps to a brands
table, the brand
array is coming back empty.
这里是否有明显的需要更改的地方?
Is there anything obvious here that needs to be changed?
$product = Product::with('images')->with('brand')->select($fields)->where('display', '=', 1)->find($id);
//产品型号
class Product extends Eloquent {
...
public function brand()
{
return $this->belongsTo('Brand');
}
//品牌模型
class Brand extends Eloquent {
...
public function products()
{
return $this->hasMany('Product');
}
推荐答案
您有以下内容:
$product = Product::with('images', 'brand')
->select($fields)
->where('display', 1)
->find($id);
对于brand
,您会得到null
,这可能是因为您有一些特定的字段,而且很可能没有从products
表中选择foreing_key
来创建与Brand
的关系,因此,如果您的products
表包含brand
表的foreign_key
(可能是brand_id
),那么您也必须从products
表中选择该foreign_key
.因此,只需在$fields
变量中添加该foreign_key/brand_id
.没有关系生成器键(FK
),将不会加载Brand
.
You are getting null
for brand
and it could be because you have some specific fields and most probably you didn't select the foreing_key
from the products
table that creates the relationship with Brand
, so if your products
table contains the foreign_key
(probably brand_id
) of brand
table then you have to select that foreign_key
from the products
table too. So, just add that foreign_key/brand_id
in the $fields
variable. Without the relation builder key (FK
) the Brand
won't be loaded.
这篇关于Laravel雄辩with()->返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!