有一个问题,不知道必须解决 我有三张桌子
与以上三个表之间的关系
category_type has many categories
和
category has many post
现在我要在数据库中查询以下数据
我想获得category_type
是World News
的所有帖子
1个帖子模型
<?php
namespace App;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function tags()
{
return $this->belongsToMany('App\Tag','post_tags')->withTimestamps();
}
public function categories()
{
return $this->belongsToMany('App\Category','category_posts');
}
public function getRouteKeyName()
{
return 'slug';
}
public function getCreatedAtAttribute($value)
{
return Carbon::parse($value)->diffForHumans();
}
public function author()
{
return $this->belongsTo(Author::class);
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
public function type(){
return $this->belongsTo(Type::class);
}
public function posts()
{
return $this->belongsToMany('App\Post','category_posts');
}
}
3- Category_Type模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Type extends Model
{
public function categories(){
return $this->hasMany(Category::class);
}
}
任何人有想法吗?
答案 0 :(得分:0)
您可以通过对帖子模型中定义的关系使用whereHas
过滤器来获取所有帖子
$type = 'World News';
$posts = Post::whereHas('categories.type', function ($query) use($type) {
$query->where('name', '=', $type);
})->get();