Laravel Eloquent with()-> 返回 null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24130410/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel Eloquent with()-> returning null
提问by Jazzy
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.
我正在尝试使用 Eloquent 来获取具有brand_id
映射到brands
表的列的特定产品,该brand
数组返回空。
Is there anything obvious here that needs to be changed?
这里有什么明显的需要改变的吗?
$product = Product::with('images')->with('brand')->select($fields)->where('display', '=', 1)->find($id);
//Product model
//产品型号
class Product extends Eloquent {
...
public function brand()
{
return $this->belongsTo('Brand');
}
//Brand model
//品牌型号
class Brand extends Eloquent {
...
public function products()
{
return $this->hasMany('Product');
}
回答by The Alpha
You have this:
你有这个:
$product = Product::with('images', 'brand')
->select($fields)
->where('display', 1)
->find($id);
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.
你得到null
的brand
,它可能是因为你有一些特定的领域和最可能是你没有选择foreing_key
从products
创建与关系表Brand
,因此,如果您的products
表包含的foreign_key
(可能brand_id
)的brand
表,那么你必须选择foreign_key
从该products
表也。所以,只要添加foreign_key/brand_id
的$fields
变量。没有关系构建器键 ( FK
)Brand
将不会被加载。