【问题标题】:Laravel 4:: Returning models and its relationshipLaravel 4:: 返回模型及其关系
【发布时间】:2013-07-04 17:04:53
【问题描述】:

我想退回模型及其部分关系

EX::

用户模型

public function comments() 
{
    return $this->hasMany('comments');
}

评论模型

public function user() 
{
    return $this->belongsTo('user');
}

我可以返回与评论相关的所有 cmets 和用户名吗?

想要的效果是

    $comment = Comments::find($id);
    $comment->user;
    return $comment;

这将返回一条评论和关联的用户完整模型。我只需要用户名。如果我打电话给Comments::all(),这不起作用

提前谢谢你。

【问题讨论】:

    标签: php json laravel


    【解决方案1】:

    您正在寻找 Eloquent 的 Eager Loading

    假设您的 Comments 模型有一个方法 user():

    public function user()
    {
        return $this->belongsTo('User');
    }
    

    您应该可以在控制器中执行此操作:

    $comments = Comments::with('user')->where('post_id', $post_id);
    
    // Return JSON, as is Laravel's convention when returning 
    // Eloquent model directly
    return $comments;
    

    你也可以做相反的事情:

    假设你的用户模型有一个方法'cmets()',像这样:

    public function comments()
    {
        return $this->hasMany('Comment');
    }
    

    在您的控制器内部,您应该能够执行以下操作,假设您有可用的用户的 $id:

    $user = User::with('comments')->find($id);
    
    // Return JSON, as is Laravel's convention when returning 
    // Eloquent model directly
    return $user;
    

    【讨论】:

      猜你喜欢
      • 2015-04-18
      • 2014-08-03
      • 2014-11-23
      • 2014-10-15
      • 2017-11-23
      • 2020-11-06
      • 2013-10-28
      • 2013-06-04
      • 1970-01-01
      相关资源
      最近更新 更多