【问题标题】:Laravel and eloquent returning results from a many to many relationshipLaravel 和雄辩的返回结果来自多对多关系
【发布时间】:2014-11-24 12:57:50
【问题描述】:

在我的网站中,我有一个项目表,它与另一个表 project_user 具有多对多关系,

在项目表中,我会有一个看起来像这样的行,

| ID  |  NAME       |
|-----|-------------|
|  1  | Project 1   |

在 project_user 表中,我有一些看起来像这样的行,

| ID  |  PROJET_ID  | USER_ID |
|-----|-------------|---------|
|  1  |      1      |    2    | 
|  1  |      1      |    4    |
|  1  |      1      |   10    | 

项目模型是这样的,

    class Project extends Eloquent {

    protected $fillable = [
        'name',
        'description',
        'total_cost',
        'start_date',
        'finish_date',
        'sales_person',
        'project_manager',
        'client_id',
        'organisation_id',
        'user_id'
    ];

    public function collaborators() {
        return $this->belongsToMany('User');
    }
}

用户表的模型如下所示,

class User extends Eloquent implements UserInterface, RemindableInterface {

    use UserTrait, RemindableTrait;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = array('password', 'remember_token');

    public function users()
    {
        return $this->belongsToMany('Project');
    }
}

我想知道的是如何从数据库中获取项目以及相关用户的用户详细信息?我目前正在尝试这个,

 $project = Project::whereHas('user', function($q)
        {
            //$q->where('user_id', '=', ResourceServer::getOwnerId());

        })->get();

【问题讨论】:

    标签: php laravel orm relational-database eloquent


    【解决方案1】:

    我想你的关系是project 而不是users,所以很简单:

    $user->load('projects.users');
    
    $user->projects; // collection of user's projects
    
    $user->projects->first()->collaborators; // collection of users in signle project
    

    如果你只想要一个项目,那么你可以这样做:

    $user->projects()->find($projectId)->collaborators;
    

    你尝试的方式也可以:

    Project::whereHas('collaborators', function ($q) {
       $q->where( .. );
    })->with('collaborators')->get();
    

    【讨论】:

      猜你喜欢
      • 2018-04-11
      • 2016-11-03
      • 2013-01-22
      • 1970-01-01
      • 1970-01-01
      • 2014-10-23
      • 2012-10-08
      • 2018-10-27
      • 2018-03-28
      相关资源
      最近更新 更多