我希望产品有标签:手机,第8次和苹果(iphone 8)
使用mysql时查询是什么?
使用Laravel Eloquent ORM时代码是什么?
抱歉我的英语不好。非常感谢!
---更新---
这是我的查询解决方案,它返回我想要的产品(iPhone 8),但它不是一个好的解决方案
SELECT *
FROM products
WHERE id IN (
SELECT product_id
FROM maps
JOIN tags ON maps.tag_id = tags.id
WHERE tags.name = "phone"
AND product_id IN (
SELECT product_id
FROM maps
JOIN tags ON maps.tag_id = tags.id
WHERE tags.name = "8th"
AND product_id IN (
SELECT product_id
FROM maps
JOIN tags ON maps.tag_id = tags.id
WHERE tags.name = "apple"
)
)
)
答案 0 :(得分:0)
您可以使用Eloquent和Collections获取所有产品。
$tags = Tag::whereIn('name', array('phone', '8th', 'apple'))->with('products')->get();
$products = (collect($tags->pluck('products')))->collapse()->unique('id');
在标签实体中设置产品关系。
class Tag extends Model
{
public function products()
{
return $this->belongsToMany('App\Product', 'maps', 'tag_id', 'product_id');
}
}
答案 1 :(得分:0)
首先,您需要在模型中添加关系。
产品型号:
public function tags()
{
return $this->belongsToMany(\App\Tag::class, 'maps', 'product_id', 'tag_id');
}
标签型号:
public function products()
{
return $this->belongsToMany(\App\Product::class, 'maps', 'tag_id', 'product_id');
}
现在,为了获得所需的产品,您可以执行以下操作:
$products = Product::whereHas('tags', function ($query) {
$query->where('name', 'phone')
->orWhere('name', '8th')
->orWhere('name', 'apple');
})
->get();
如果你有一个标签名称数组,那么你可以这样做:
$products = Product::whereHas('tags', function ($query) use ($tagNames) {
$query->whereIn('name', $tagNames);
})
->get();
答案 2 :(得分:0)
以下是查询
SELECT
*
FROM
products
WHERE id IN(
SELECT
DISTINCT maps.product_id
FROM
maps
INNER JOIN tags ON maps.tag_id = tags.id
WHERE
tags.name IN ('phone', '8th', 'apple')
);
答案 3 :(得分:0)
感谢所有答案,此问题已得到解决
Mysql查询:
SELECT *
FROM products
WHERE id IN (SELECT product_id FROM maps JOIN tags ON maps.tag_id = tags.id WHERE tags.name = "phone")
AND id IN (SELECT product_id FROM maps JOIN tags ON maps.tag_id = tags.id WHERE tags.name = "8th")
AND id IN (SELECT product_id FROM maps JOIN tags ON maps.tag_id = tags.id WHERE tags.name = "apple");
Laravel代码:
$tags = ['phone','8th','apple'];
$products = new Product();
foreach ($tags as $value) {
$query = Map::select('product_id')
->join('tags','maps.tag_id','=','tags.id')
->where('tags.name',$value);
$products = $products->whereIn('id',$query);
}
$products = $products->get();