php - Laravel.获取一条相关记录

标签 php mysql laravel orm

有两种模型:类别和帖子。

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/

相关文章:

javascript - 如何使用 AJAX 重新加载 Laravel @includes?

php - Laravel 5.3 - 如何跨多个数据库执行查询?

php - 在生产服务器 codeigniter 3.1.2(PHP) session 销毁自动从 facebook 图形 API 重定向?

php - 如何在 php 和 mysql 中使用 select 选项更新表

php - 有谁知道为什么这个 PHP 不会将数据写入我的数据库?

mysql - 获取 MySQL 中的底层主键 (InnoDB)

mysql - 按时间排序,仅显示唯一的

mysql - 用MySQL存储十进制数

php - php解析/语法错误帮助

php - 违反完整性约束 : 1452 Cannot add or update a child row in Laravel 5. 2