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

Jer*_*emy 2 php mysql laravel

我在SQL中为空.

我有两个表workstypes.

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

type包含ID,nameslug.

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

我与模特工作的关系

public function type()
{
    return $this->belongsTo('App\Models\Type');
}
Run Code Online (Sandbox Code Playgroud)

我的模型类型的关系

public function works()
{
    return $this->hasMany('App\Models\Work');
}
Run Code Online (Sandbox Code Playgroud)

我试过这个,但这完全错了

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

谢谢 !

San*_*esh 5

您的关系被定义为type并且您正在加载types.

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