简体   繁体   English

使用WHERE方法查询Laravel中的关系

[英]Query a relationship in Laravel with WHERE method

I have a model called "User", which "belongsToMany" Items. 我有一个名为“ User”的模型,该模型“属于ToMany”项。 This relationship works fine, so I can easily do something like this: 这种关系很好,所以我可以轻松地执行以下操作:

User::find(4)->items->find(1)->name

Now, I would like to do something like this: 现在,我想做这样的事情:

User::find(4)->items->where('name', '=', 'stick')->get()

I would expect the code to return all the user's items with the name "stick", but unfortunately that is not what happens. 我希望代码返回名称为“ stick”的所有用户项目,但不幸的是,这不会发生。 I receive this error: 我收到此错误:

"Call to undefined method Illuminate\Database\Eloquent\Collection::where()"

I also tried to build a query scope: 我也尝试建立查询范围:

public function scopeName($query, $name)
{
    return $query->whereName($name);
}

The query scope works when I do something like this: 当我执行以下操作时,查询范围将起作用:

Item::name('SC')->get()

but

User::find(4)->items->name('SC')->get() 

still does not work. 仍然无法正常工作。

Can you help me returning all the user's items, which have the name 'stick'? 您能帮我退还所有用户名称为“ stick”的物品吗?

If you're looking to just get a single user's items named "stick", this is how you would do it: 如果您只想获取单个用户的名为“ stick”的商品,则可以这样做:

$stickItems = Item::whereUserId(4)->whereName('stick')->get();

Here we are using Eloquent's dynamic where methods , but you could rewrite it like so: 在这里,我们使用Eloquent的动态where方法 ,但是您可以这样重写它:

$stickItems = Item::where('user_id', '=', 4)->where('name', '=', 'stick')->get();

That should get you what you want. 那应该给您您想要的。

You have to call the items() method, not use the magic property: 您必须调用items()方法,而不要使用magic属性:

User::find(4)->items()->where('name', 'stick')->get();
//                  ^^

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM