2017-06-13 64 views
0

是否可以创建一个快速方法以从一对多关系中返回第一个模型?这里是我的代码,从模型文件:从Laravel的hasMany关系中返回第一个模型

public function books() { 
    return $this->hasMany('App\Models\Book'); 
} 

public function first_book() { 
    return $this->book()->first(); 
} 

这是我得到的错误:

'Call to undefined method Illuminate\Database\Query\Builder::addEagerConstraints()'

我想用这个的原因是,这样我可以收集第一使用with()方法记录,例如:

$authors = Author::with('first_book')->select('*'); 

我在Datatables中使用这些记录。

回答

1

要使用with()您的方法必须从关系方法返回一个集合,因为您的关系是hasMany。所以,你可以做的是:

public function books() { 
    return $this->hasMany('App\Models\Book'); 
} 

public function first_book() { 
    return $this->hasMany('App\Models\Book')->limit(1); 
} 

这将返回一个集合与您的第一个项目,所以你还是要调用first()

$authors = Author::with('first_book')->select('*'); 
$authors->first_book->first(); 
+0

我会替换返回$ this-> hasMany('App \ Models \ Book') - > limit(1);返回$ this-> books() - > limit(1); – Brad

0

一个关系,可以是急于装了回一个问题。 first()函数返回一个雄辩的对象。

的解决方案是限制这个查询的结果的数量,像这样:

public function first_book() { 
    return $this->books()->take(1); 
} 

$author->first_book仍然将是一个集合,但它只会包含第一个相关的书在你的数据库。

0

一对一的关系是一个非常基本的关系。例如

public function books() 
    { 
     return $this->hasOne('App\Models\Book'); 
    }