有两种模型:类别和帖子。
class Category extends Model
{
public function posts()
{
return $this->hasMany('App\Post','category_id');
}
}
class Post extends Model
{
public function category()
{
return $this->belongsTo('App\Category');
}
}
//Get data
$data = Category::with(['posts' => function($query){
$query->orderBy('id','desc')->first();
}])->get();
在这种情况下,将显示所有类别,并且仅显示一篇帖子。我需要从每个类别中获取一个记录帖子。
示例:
类别 1 - 帖子 1
类别 2 - 帖子 2
类别 3 - 帖子 5
类别 4 - Post15
一个类别 - 该类别的最后一篇文章。
最佳答案
您有一个包含许多帖子
的类别
,但您只想获取最新的帖子,以便添加另一个关系。
// Category.php
class Category extends Model
{
// This gets ALL posts
public function posts()
{
return $this->hasMany('App\Post','category_id');
}
// This gets the most recent post
// I am ordering by created_at instead of ID, but you can use ID
// if it makes sense for your application)
public function mostRecentPost()
{
return $this->hasOne('App\Post','category_id') // hasOne is the key here
->orderBy('created_at', 'DESC');
}
}
然后当你想使用它时...
$data = Category::with('mostRecentPost')->get();
关于php - Laravel.获取一条相关记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39731423/