0

I am using laravel, I have a main table with 'projects' and a table with 'users', an intermediate table linking the two as a many-to-many relationship.

Now I want to display a list of projects, but if they are over 'projects.max_people' then they should be hidden from this list, how do I do this in laravel?

The problem is im 'get()'ing the users in the view, after I did Project::get()... how do I add this where condition?

4

1 回答 1

0

您应该创建一个名为 ProjectUser 左右的新对象。在这个对象中应该包含一个“project_id”和“user_id”。

然后,您的 Project 模型将如下所示:

<?php

class Project extends \Eloquent
{
    protected $table = 'projects';

    public function projectUsers(){
       $this->hasMany('ProjectUser', 'project_id');
    }
}

用户类:

<?php

class Project extends \Eloquent
{
    protected $table = 'projects';

    public function projectUsers(){
       $this->hasMany('ProjectUser', 'user_id');
    }
}

ProjectUser 类:

class ProjectUser extends \Eloquent
{
    protected $table = 'project_users';

    public function project(){
       $this->belongsTo('Project'`enter code here`, 'project_id');
    }

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

现在,您可以像这样获取项目的用户:

$projects = Project::with('projectUsers.user')->get();

遍历这些对象时,您可以像这样访问用户:

@foreach($projects as $project)

   @foreach($project->projectUsers as $projectUser)

      {{ $projectUser->user->id }}

   @endforeach

@endforeach
于 2015-07-29T17:27:09.233 回答