显示项目在laravel添加的用户

问题描述 投票:0回答:1

我有一个用户,一个项目,project_user表,通常我可以证明,创建了一个项目只有他自己的项目特定的用户,从用户管理项目的创建者可以将其他用户添加到项目,现在我有一个问题使所添加的用户看到他/加过她的项目,我用Auth()->user->projects显示在用户的他/她的项目创建一个特定的记录下来,任何想法如何,我可以解决这个问题。

laravel
1个回答
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会显示当前用户添加到项目中。

© www.soinside.com 2019 - 2024. All rights reserved.