Php 为什么Laravel关系会阻止对查询生成器方法的调用?

Php 为什么Laravel关系会阻止对查询生成器方法的调用?,php,orm,laravel-4,eloquent,Php,Orm,Laravel 4,Eloquent,我想查找属于id=1的用户的所有患者 这项工作: $data = Patient::where('user_id', '=', 1) ->with('method', 'images')->get()->toJson(); 这不起作用: $data = User::find(1)->patients->with('method', 'images')->get()->toJson(); 它说: Call to undefined me

我想查找属于
id=1的用户的所有患者

这项工作:

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

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

Call to undefined method Illuminate\Database\Eloquent\Collection::with()
为什么错了?可以纠正吗?

试试这个

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


代码不起作用的原因是,所有雄辩的关系声明都会返回不同的结果,这取决于您是尝试将关系作为属性还是作为方法访问(使用
()
还是不使用
()


尝试
User::find(1)->patients()->with('method','images')->get()->toJson()-行吗?哦。。等一下!是的,它能工作。:)你能不能把它变成一个答案,这样我就可以正确地投票了?我以前从未将()用于关系。酷-我已将我的评论作为答案发布给您。请尝试解释一下()在做什么?它基本上是返回患者模型本身,允许您链接进一步的操作,而不是患者结果。而且集合是不可链接的。它不是可以与查询生成器方法一起使用的对象,因为它不是查询/生成器的实例?我明白了。有趣。它们基本上返回不同的类型。但是您是对的,如果您使用
User::find(1)->patients
,则无法链接查询,因为此时已执行查询(elount将检索ID=1的用户的所有患者),因此无法链接。但是,您可以开始使用有说服力的收集方法(例如,
User::find(1)->patients->toArray()
User::find(1)->patients()->with('method', 'images')->get()->toJson();
// Return you chainable queries    
$query = User::find(1)->patients()->... 
// Return you collection of patients
$patientsCollection = User::find(1)->patients;