【问题标题】:Laravel.get one related recordLaravel.get 一条相关记录
【发布时间】:2016-09-27 18:01:20
【问题描述】:

有两种模型:Category 和 Post。

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 - Post2
类别 3 - Post5
类别 4 - Post15
一个类别 - 最后一个发布此类别。

【问题讨论】:

    标签: php mysql laravel orm


    【解决方案1】:

    您有一个 Category 和许多 Posts,但您只想获取最新的帖子,以便添加另一个关系。

    // 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();
    

    【讨论】:

    • 糟糕!我误解了这个问题:-)
    猜你喜欢
    • 1970-01-01
    • 2015-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多