从 Laravel 中的 hasMany 关系返回第一个模型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44524888/
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
Returning the first model from a hasMany relationship in Laravel
提问by f7n
Is it possible to create a quick method to return the first model from a one-to-many relationship? Here is my code, from the model file:
是否可以创建一种快速方法来从一对多关系中返回第一个模型?这是我的代码,来自模型文件:
public function books() {
return $this->hasMany('App\Models\Book');
}
public function first_book() {
return $this->book()->first();
}
This is the error I'm getting:
这是我得到的错误:
'Call to undefined method Illuminate\Database\Query\Builder::addEagerConstraints()'
'Call to undefined method Illuminate\Database\Query\Builder::addEagerConstraints()'
The reason I want to use this is so that I can collect the first record using the with() method, for example:
我想使用它的原因是我可以使用 with() 方法收集第一条记录,例如:
$authors = Author::with('first_book')->select('*');
I'm using these records with Datatables.
我将这些记录与数据表一起使用。
回答by Keshari Nandan
I might be late but for your future use and for other who want the same output try this one -
我可能会迟到,但为了您将来的使用以及其他想要相同输出的人,请尝试这个 -
// If you need the last one
// 如果你需要最后一个
public function books() {
return $this->hasOne('App\Models\Book')->latest();
}
// If you need the first entry -
// 如果你需要第一个条目 -
public function books() {
return $this->hasOne('App\Models\Book')->oldest();
}
回答by Jerodev
A relation that can be eager loaded has to return a query. The first()
function returns an eloquent object.
可以预先加载的关系必须返回查询。该first()
函数返回一个 eloquent 对象。
The solution is to limit the number of results of this query like so:
解决方案是限制此查询的结果数量,如下所示:
public function first_book() {
return $this->books()->take(1);
}
$author->first_book
will still be a collection, but it will only contain the first related book in your database.
$author->first_book
仍将是一个集合,但它只会包含您数据库中的第一本相关书籍。
回答by Yaser Darzi
A one-to-one relationship is a very basic relation. For example
一对一的关系是一种非常基本的关系。例如
public function books()
{
return $this->hasOne('App\Models\Book');
}
回答by thefallen
To use with()
your method has to return a collection from a relation method, because your relation is hasMany. So what you could do is:
要使用with()
您的方法必须从关系方法返回一个集合,因为您的关系是 hasMany。所以你可以做的是:
public function books() {
return $this->hasMany('App\Models\Book');
}
public function first_book() {
return $this->hasMany('App\Models\Book')->limit(1);
}
Which would return a collection with your first item, so you' still have to call first()
:
这将返回一个包含您的第一个项目的集合,因此您仍然必须调用first()
:
$authors = Author::with('first_book')->select('*');
$authors->first_book->first();