向laravel中的添加用户显示项目

时间:2019-02-02 14:50:33

标签: laravel

我有一个用户,一个项目和一个project_user表,通常我可以显示一个仅创建了自己项目的用户,该项目的创建者可以将其他用户添加到该项目中。遇到使添加的用户也看到他/她添加的项目时遇到的问题,我使用Auth()->user->projects来显示他/她创建的项目的特定登录用户,我该如何解决这个问题。

1 个答案:

答案 0 :(得分:0)

下面是如何能够实现这样的示例:

架构

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('content');
    $table->timestamps();
});

Schema::create('projects', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('user_id');
    $table->string('content');
    $table->timestamps();
});

Schema::create('project_user', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('project_id');
    $table->integer('user_id');
    $table->timestamps();
});

模型

class User extends Model
{
    protected $fillable = ['content'];

    public function ownProjects()
    {
        return $this->hasMany(Project::class);
    }

    public function projectsIamAddedTo()
    {
        return $this->belongsToMany(Project::class);
    }
}
class Project extends Model
{
    protected $fillable = ['content', 'user_id'];

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

    public function addedUsers()
    {
        return $this->belongsToMany(User::class);
    }
}

控制器操作

$creator = User::create(['content' => 'hello creator']);
$project = Project::create(['content' => 'hello project', 'user_id' => $creator->id]);

// Create the user to be added
$addedUser = User::create(['content' => 'hello user']);

// Add the user to the project
$project->addedUsers()->attach($addedUser->id);

// Alternatively: 
// $addedUser->projectsIamAddedTo()->attach($project->id);

// return $creator->ownProjects; // Returns the projects owned by the user

return $addedUser->projectsIamAddedTo; // Returns the projects the user was added to

现在,Auth()->user->ownProjects将显示当前用户已创建的项目,Auth()->user->projectsIamAddedTo将显示当前用户已添加到的项目。