从Laravel中的hasMany关系返回第一个模型

f7n*_*f7n 3 datatables laravel eloquent

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

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

public function first_book() {
    return $this->book()->first();
}
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误:

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

我想使用它的原因是为了可以使用with()方法收集第一条记录,例如:

    $authors = Author::with('first_book')->select('*');
Run Code Online (Sandbox Code Playgroud)

我正在将这些记录与数据表一起使用。

小智 13

我可能已经晚了,但为了您将来使用以及其他想要相同输出的人,请尝试使用此方法-

//如果您需要最后一个

public function books() {
    return $this->hasOne('App\Models\Book')->latest();
}
Run Code Online (Sandbox Code Playgroud)

//如果您需要第一个条目-

public function books() {
        return $this->hasOne('App\Models\Book')->oldest();
    }
Run Code Online (Sandbox Code Playgroud)


Jer*_*dev 12

可以预先加载的关系必须返回查询。该first()函数返回一个 eloquent 对象。

解决方案是限制此查询的结果数量,如下所示:

public function first_book() {
    return $this->books()->take(1);
}
Run Code Online (Sandbox Code Playgroud)

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


the*_*len 8

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

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

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

这将返回包含您的第一个项目的集合,因此您仍然需要调用first()

$authors = Author::with('first_book')->select('*');
$authors->first_book->first();
Run Code Online (Sandbox Code Playgroud)


Ric*_*ard 5

在 laravel 9.x 中,您可以使用latestOfManyoldestOfMany像这样;

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

// Get the first inserted child model
public function first_book() {
   return $this->hasOne('App\Models\Book')->oldestOfMany();

}

// Get the last inserted child model
public function last_book() {
   return $this->hasOne('App\Models\Book')->latestOfMany();

}

Run Code Online (Sandbox Code Playgroud)

奖励:如果您使用的是 php 5.5 或更高版本,您可以使用范围解析运算符获取完全限定的类名,看起来很干净,即;

// your relationship
public function books() {
    return $this->hasMany(Book::class);
}

// Get the first inserted child model
public function first_book() {
   return $this->hasOne(Book::class)->oldestOfMany();

}

// Get the last inserted child model
public function last_book() {
   return $this->hasOne(Book::class)->latestOfMany();

}
Run Code Online (Sandbox Code Playgroud)

Laravel 文档链接