【问题标题】:Laravel get all User information in relation ship methodLaravel 以关系方式获取所有用户信息
【发布时间】:2016-02-23 10:33:27
【问题描述】:

在 User 和 Post 模型中,我创建了简单的 RelationShip 作为:

帖子模型:

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

用户模型:

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

在数据库中创建新项目我在帖子表中有user_id,例如1。将此代码用于控制器后:

$all_records = \App\Posts::all();

我在帖子表中没有 user_id 信息。例如,posts 表中的 user_id 是 1,我希望将子查询作为 id 为 1 的所有用户表

【问题讨论】:

    标签: laravel


    【解决方案1】:

    问题解决了:

    $all_records = \App\Posts::with('user')->get();
    

    【讨论】:

      【解决方案2】:

      如果您想要 user_id 为 1 的所有帖子,那么您可以说:

      User::find(1)->posts;

      【讨论】:

        猜你喜欢
        • 2023-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-03
        相关资源
        最近更新 更多