繁体   English   中英

Laravel 在 ManyToMany 中获取哪些类别属于登录用户

[英]Laravel get which Categories belong to logged user in ManyToMany

在我的简单博客 Web 应用程序中,我有一些categoriesusers存储在数据库中,每个category可能属于一个或多个用户,我尝试让它们显示每个登录的用户,为了实现这个场景,我有以下表格:

Schema::create('users', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->unsignedBigInteger('user_id')->index()->nullable();
    $table->foreign('user_id')->references('id')->on('users');
    $table->string('name')->nullable();
    $table->string('family')->nullable();
    $table->string('username')->unique();

    $table->rememberToken();
    $table->softDeletes();
    $table->timestamp('created_at')->useCurrent();
    $table->timestamp('updated_at')->useCurrent();
});

Schema::create('categories', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->unsignedBigInteger('category_id')->index()->nullable();
    $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
    $table->string('category_name');
    $table->softDeletes();
    $table->timestamp('created_at')->useCurrent();
    $table->timestamp('updated_at')->useCurrent();
});

然后,创建many to many表:

Schema::create('category_user', function (Blueprint $table) {
    $table->unsignedBigInteger('user_id')->index();
    $table->unsignedBigInteger('category_id')->index();
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
    $table->primary(['user_id','category_id']);
});

现在如何使用此代码获取已登录用户的类别:

$categories = Category::whereNull('category_id')
    ->with(['childrenCategories', 'users' => function ($query) {
        //$query->where('id',auth()->user()->id);
    }])
    ->withCount('posts')
    ->get();

您可以使用whereHas 查询关系是否存在,以仅获取属于经过身份验证的用户的类别。

$categories = Category::whereNull('category_id')
    ->whereHas('users', function ($query) {
        $query->where('id', auth()->user()->id);
    })
    ->with([
        'childrenCategories', 
        'users' => function ($query) {
            $query->where('id', auth()->user()->id);
        }
    ])
    ->withCount('posts')
    ->get();

在您的用户模型中,添加两个模型之间的关系:

public function categories()
{
    return $this->belongsToMany('App\Models\Category');
}

在您的控制器内:

 $user = App\Models\User::find(1);

现在您可以获得用户的类别

foreach ($user->categories as $category) {
//
}

https://laravel.com/docs/8.x/eloquent-relationships#many-to-many

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM