如何在Laravel Eloquent中使用join

时间:2018-07-17 12:28:51

标签: php database laravel-5.5

有一个问题,不知道必须解决 我有三张桌子

  1. 帖子
  2. 类别
  3. category_type

与以上三个表之间的关系

category_type has many categories 

category has many post 

现在我要在数据库中查询以下数据

我想获得category_typeWorld 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);
    }
}
2-类别模型

<?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);
    }
}

任何人有想法吗?

1 个答案:

答案 0 :(得分:0)

您可以通过对帖子模型中定义的关系使用whereHas过滤器来获取所有帖子

$type = 'World News';
$posts = Post::whereHas('categories.type', function ($query) use($type) {
    $query->where('name', '=', $type);
})->get();