我用这种麻烦看了很多搜索结果,但我无法让它起作用。
用户模型
<?php namespace Module\Core\Models;
class User extends Model {
(...)
protected function Person() {
return $this->belongsTo( 'Module\Core\Models\Person', 'person_id' );
}
(...)和人模型
<?php namespace Module\Core\Models;
class Person extends Model {
(...)
protected function User(){
return $this->hasOne('Module\Core\Models\User', 'person_id');
}
(...)现在,如果我使用User::find(1)->Person->first_name它的工作。我可以从用户模型中获得人员关系。
但是..。User::with('Person')->get()对未定义方法Illuminate\Database\Query\Builder::Person()的调用失败
我做错什么了?我需要一个收集所有的用户与他们的个人信息。
发布于 2015-03-13 17:10:39
您必须将关系方法声明为public。
为什么会这样呢?让我们看一看with()方法:
public static function with($relations)
{
if (is_string($relations)) $relations = func_get_args();
$instance = new static;
return $instance->newQuery()->with($relations);
}由于方法是从静态上下文中调用的,所以不能只调用$this->Person()。相反,它会创建模型的一个新实例,并创建一个查询生成器实例,并对此调用with等等。最后,必须从模型外部访问关系方法。这就是为什么可见性必须是public。
https://stackoverflow.com/questions/29036397
复制相似问题