Jaz*_*zzy 9 php mysql orm laravel eloquent
我正在尝试使用Eloquent来获取具有brand_id映射到brands表的列的特定产品,该brand数组将返回空白.
这里有什么明显的东西需要改变吗?
$product = Product::with('images')->with('brand')->select($fields)->where('display', '=', 1)->find($id);
Run Code Online (Sandbox Code Playgroud)
//产品型号
class Product extends Eloquent {
...
public function brand()
{
return $this->belongsTo('Brand');
}
Run Code Online (Sandbox Code Playgroud)
//品牌模型
class Brand extends Eloquent {
...
public function products()
{
return $this->hasMany('Product');
}
Run Code Online (Sandbox Code Playgroud)
The*_*pha 13
你有这个:
$product = Product::with('images', 'brand')
->select($fields)
->where('display', 1)
->find($id);
Run Code Online (Sandbox Code Playgroud)
你得到null了brand,它可能是因为你有一些特定的字段,很可能你没有foreing_key从products创建关系的表中选择Brand,所以如果你的products表包含foreign_key(可能brand_id)brand表,那么你必须foreign_key从该products表也.所以,只需foreign_key/brand_id在$fields变量中添加它即可.如果没有关系构建器key(FK),Brand则不会加载.