如何使用Laravel进行此SQL查询?

时间:2017-05-15 18:31:14

标签: php mysql laravel

我在SQL中为null。

我有两张表workstypes

works包含引用工作类型的foreign_key type_id(在我的数据库中,这是类型的ID)。

type包含IDnameslug

我想从特定类型获得所有作品。示例:获取类型为website的所有作品(网站为slug)。

我对模特作品的关系

public function type()
{
    return $this->belongsTo('App\Models\Type');
}

我的模型类型

的关系
public function works()
{
    return $this->hasMany('App\Models\Work');
}

我试过了,但这完全错了

Work::with('types')->where('slug', $request->get('type'));

谢谢!

1 个答案:

答案 0 :(得分:5)

您的关系定义为type,您正在加载types

$works = Work::whereHas('type', function ($query) use ($request) {
    $query->where('slug', $request->get('type'));
})->get();