Laravel 雄辩问题:方法不存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43394780/
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 issue: Method does not exist
提问by Ilan Finkel
I have 2 tables, Clients and Companies each Company has many clients and each client has one company
我有 2 个表,客户和公司,每个公司有很多客户,每个客户有一家公司
this is my models:
这是我的模型:
class Client extends Model
{
public function company(){
return $this->hasOne('App\Company');
}
}
class Company extends Model
{
public function clients(){
return $this->hasMany('App\Client');
}
}
I'm trying to get a list of all the clients of a company and this is what I tried to do:
我正在尝试获取公司所有客户的列表,这就是我尝试做的:
$clients = Company::where('guid',$guid)->clients()->all();
I'm getting this error:
我收到此错误:
BadMethodCallException in Macroable.php line 74:
Method clients does not exist.
thank you for your help!
感谢您的帮助!
回答by Saeed Prez
$clients = Company::where('guid',$guid);
This returns the Builder class, so when you then add ->clients()
it will give you error because the builder class does not have the clients method, your model does.
这将返回 Builder 类,因此当您添加->clients()
它时会出现错误,因为 builder 类没有 clients 方法,而您的模型有。
The correct code would be..
正确的代码是..
$clients = Company::with('clients')->where('guid',$guid)->get();
PS. Don't use ->all()
unless it's something like $companies = Company::all()
附注。->all()
除非它是类似的东西,否则不要使用$companies = Company::all()
回答by Vinicius Luiz
Your relationship defined at the model must be called like this:
您在模型中定义的关系必须像这样调用:
$clients = Company::where('guid',$guid)->clients;
It will query all clients at your company, don't use the method all() to do this. And on your Client model do the same to search by the company.
它将查询您公司的所有客户,不要使用 all() 方法来执行此操作。并在您的客户模型上执行相同的操作以按公司进行搜索。
$company = Client::where('id', 1)->company;