简体   繁体   English

为什么Laravel关系会阻止对查询构建器方法的调用?

[英]Why do Laravel relationships prevent calls to query builder methods?

I want to find all patients that belong to a user where id = 1 我想找到属于id = 1的用户的所有患者

This works: 这有效:

$data = Patient::where('user_id', '=', 1)
        ->with('method', 'images')->get()->toJson();

This doesn't work: 这不起作用:

$data = User::find(1)->patients->with('method', 'images')->get()->toJson();

It says: 它说:

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

Why is it wrong? 为什么这是错的? Could it be corrected? 可以纠正吗?

The reason your code doesn't work is all Eloquent relationship declaration returns different result depending on whether you are trying to access the relationship as property or as method (with () or without () ). 您的代码不起作用的原因是所有Eloquent关系声明都返回不同的结果,具体取决于您是尝试以属性还是以方法(with ()without () )来访问关系。

// Return you chainable queries    
$query = User::find(1)->patients()->... 
// Return you collection of patients
$patientsCollection = User::find(1)->patients;

尝试

User::find(1)->patients()->with('method', 'images')->get()->toJson();

Try this 尝试这个

$patient = New Patient;
$data = $patient->where('user_id','=',1)->with('method','images')->get()->toJson();

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

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