【发布时间】:2021-11-08 20:17:39
【问题描述】:
我无法理解这一点。我有三个表(缩写):
*images*
id | label | …
*keywords*
id | label | …
*image_keyword*
image_id | keyword_id
我在模型中定义了它们的多对多关系:
*Image.php*
public function keywords()
{
return $this->belongsToMany(Keyword::Class);
}
*Keyword.php*
public function images()
{
return $this->belongsToMany(Image::Class);
}
有一次我通过这段代码实现了一个惰性模糊搜索:
$terms = explode(' ', $request->input('q'));
$query = DB::connection('pia')->table('images');
foreach($terms as $k => $term) {
$query->where(DB::raw('lower(images.title)'), 'like', '%' . strtolower($term) . '%');
}
return response()->json($query->get());
目前还不错。现在我很想将关键字添加到我传递回前端的图像对象中,但我没有设法产生一个有效的解决方案。我不是数据库设计和代码方面的专家。
我希望将关键字与图像对象一起传递,如下所示:
{
'id': 123,
'label': 'Dog',
'file': '/data/images/dog.jpg',
'keywords': [
{
'id': 312,
'label': 'Animal'
},
{
'id': 313,
'label': 'Pet'
],
}
我尝试了连接,但无法产生任何工作结果。
【问题讨论】: