eloquent是指相关模型的一列

时间:2017-03-01 11:11:01

标签: eloquent

我有三张桌子:

categories
id, title

products
id, name

categories_products
id, category_id, product_id

我还设置了相应的模型和关系(两者都属于另一个的属性)

现在我想让所有产品属于一个类别

Category::where('title','Electronics')->first()->products()->limit(10)->get(['products.name']);

工作正常,但我也想包括每个产品的类别标题:

Category::where('title','Electronics')->first()->products()->limit(10)->get(['products.name','category.title']);

然而它返回:找不到列category.title

我认为这种关系可以解决它。

编辑:模型 - >

类别:

class Category extends Model
{

    protected $fillable = array('title');

    public function products()
    {
        return $this->belongsToMany('Product', 'categories_products', 'category_id', 'product_id');
    }
}

class Product extends Model
{

    protected $fillable = array('name');

    public function categories()
    {
        return $this->belongsToMany('Category', 'categories_products', 'product_id', 'category_id');
    }
}

1 个答案:

答案 0 :(得分:1)

您收到错误的原因是因为select()的工作原理与Product::select('id', 'name') ->with(['categories' => function($query) { return $query->select('id', 'title'); }]) ->whereHas('categories', function($query) { return $query->where('title', 'Electronics'); }) ->limit(10) ->get(); 类似,因为您正在运行类别查询,然后在没有要引用的类别表后运行产品查询选择。

查看Eager Loading。它将有助于解决很多这类问题。您的查询可以写成:

id

因为我们延迟加载你需要每个模型上的with()列,所以Laravel知道在运行查询后将关系附加到何处。

上面的categories方法会急切加载whereHas()关系,而Category方法会对当前查询设置关系约束。

<强>更新

来自$category = Category::where('title','Electronics') ->with(['products' => function($query) { return $query->select('id', 'name')->limit(10); }]) ->first(['id', 'title']); 模型的类似查询:

$category->products

然后访问产品:

console.log(this.message);
相关问题