1 回答

TA貢獻1775條經(jīng)驗 獲得超8個贊
根據(jù)模型的設(shè)置方式,這就是 Eloquent 的查詢方式
$category = Post::whereHas('comments', function($query) {
$query->where('user_id', auth()->user()->id);
})->first()->category;
更新:
這就是您的模型和表遷移的外觀
User有很多帖子和評論
public function posts()
{
return $this->hasMany(Post::class);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
Category 有很多帖子
public function posts()
{
return $this->hasMany(Post::class);
}
Post 屬于一個類別和一個用戶,有很多評論
public function category()
{
return $this->belongsTo(Category::class);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
Posts Table Migration
Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->unsignedBigInteger('category_id');
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
$table->timestamps();
});
Comment 屬于一個帖子和一個用戶
public function post()
{
return $this->belongsTo(Post::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
Comments Table Migration
Schema::create('comments', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->unsignedBigInteger('post_id');
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
$table->timestamps();
});
讓我們填充一些這樣的數(shù)據(jù)......
Database Seeder
$user = factory(User::class)->create([]);
$category = Category::create([]);
$post = $user->posts()->create(['category_id' => $category->id]);
$post->comments()->create(['user_id' => $user->id]);
并通過上面的查詢獲取經(jīng)過身份驗證的用戶評論過的帖子的類別......
希望這會有所幫助:)
- 1 回答
- 0 關(guān)注
- 229 瀏覽
添加回答
舉報