如何在 Laravel ORM Eloquent 上转换原始 sql 命令

我有 4 个表,1-> 用户,2-> 类别,3-> 评论,4-> 帖子


我想获取用户已经评论过的相关帖子的类别


SELECT kategoris.* FROM kategoris 

INNER JOIN yazis on yazis.kategori_id = kategoris.id 

INNER JOIN yorums on yorums.yazi_id = yazis.id

INNER JOIN users on users.id = yorums.user_id

where users.id = 1

http://img3.mukewang.com/61d98351000143d308780426.jpg

紫衣仙女
浏览 239回答 1
1回答

www说

根据模型的设置方式,这就是 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 MigrationSchema::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 MigrationSchema::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();});让我们填充一些这样的数据......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]);并通过上面的查询获取经过身份验证的用户评论过的帖子的类别......希望这会有所帮助:)
打开App,查看更多内容
随时随地看视频慕课网APP