【问题标题】:Laravel Eloquent to get parent, child records and child recordsLaravel Eloquent 获取父子记录和子记录
【发布时间】:2019-02-21 22:30:40
【问题描述】:

我有这些模型在括号中包含以下字段。 用户可以有很多帖子,帖子可以有很多类别。我们怎么能 使用 laravel eloquent 来实现这些。

User   [id, name]
Post   [id, user_id, post_title]
PostType [id,post_id, category_desc]

在用户模型中

public function posts(){
    return $this->hasmany('App\Post');
}

在后期模型中

public function categories(){
   return $this->hasmany('App\PostType');
}

在控制器中

$result = User::with('post')->get();

这将返回用户,每个用户都有一个帖子记录。但是如何在结果集中添加类别呢?

【问题讨论】:

    标签: mysql laravel eloquent


    【解决方案1】:

    另一种解决方案,特别是如果您想在每次获取用户时都带上帖子和帖子类别,则可以使用 User 和 Post 模型上的 $appends 数组来自动提取每个查询的这些关系。例如,您的 Post 模型将在顶部包含以下内容:

    class Post extends Model
    {
        $appends = array('categories');
    ...
    

    你的用户模型看起来像这样:

    class User extends Authenticatable
    {
        $appends = array('posts');
    ...
    

    每当您拉入用户对象时,这将自动拉入这些类别以及帖子。

    【讨论】:

    • 感谢 eResourcesInc 的替代解决方案。也会注意到这一点。
    【解决方案2】:

    您可以使用点表示法包含远距离关系:

    $result = User::with(['post', 'post.categories'])->get();
    

    【讨论】:

    • 感谢 Devon,经过测试并按预期工作。你是大师。
    猜你喜欢
    • 1970-01-01
    • 2016-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-23
    • 2014-07-14
    • 1970-01-01
    相关资源
    最近更新 更多