Laravel 从深厚的关系中获取数据

Laravel getting data from a deep relationship

我有 3 个表:

Users Baskets Items
id id id
user_id basket_id
price

我正在尝试在 eloquent 中建立一个关系,通过它我可以获得所有物品和相应的篮子,其中物品的价格是 X。我想要它以便我可以简单地使用 $ user->items(x) 并得到结果。

我不确定这是否可以单独使用关系来完成,还是我必须诉诸于编写自定义查询。

任何帮助和指导都将不胜感激!

您要找的关系是hasManyThrough

https://laravel.com/docs/7.x/eloquent-relationships#has-many-through

用户模式

public function items()
{
    return $this->hasManyThrough(Item::class, Bucket::class);
}

你想用的方式我想是不可能实现的。

可能的用法

$user->items()->where('price', x);

如果您定义自定义范围

项目模式

public function scopeWherePrice($query, $value)
{
    return $query->where('price', $value);
}

用法

$user->items()->wherePrice(x);

编辑

如果你真的想写类似$user->items(x)的代码,你可以在User Modal.

上定义一个方法

请注意,这不是关系,只是获取结果的另一种方法。

用户模式

public function items($price)
{
    return this->items()->where('price', $price)->get();
}

使用 hasManyThrough 定义模型中的关系:

用户模型

 /**
 * Get all of the items & baskets for the user.
 */
 public function items($price)
 {
    return $this->hasManyThrough('App\Items', 'App\Baskets')
        ->with('basket')
        ->where('price',$price);
 }

篮子模型

 /**
 * Get the Items's Basket.
 */
 public function basket()
 {
    return $this->belongsTo('App\Basket','basket_id');
 }

然后这样称呼它:

 $user->items(x);

这将 return 具有特定价格的相应购物篮的所有用户商品。