我有具有以下结构的表,一种产品可能有很多缺点:
product skus
id product_id
sku_prin sku
other fields other fields
如果产品表的sku_prin或skus表的sku中都存在搜索值,则应选择该行。
$search_value = "ramdom_value";
$query = product::query();
$result = $query->with(['skus' => function($q) use($search_value){
// this code won't work the orWhere cannot change the context of skus table
$q->where('sku', $search_value)->orWhere('products.sku_prin', $search_value)
}])->paginate(50);
以上是我的失败尝试。如何完成我想要的?
答案 0 :(得分:0)
一种方法是使用口才的whereHas功能
考虑您拥有这样的产品和skus模型
class Product extends Model
{
protected $table = 'product';
public function sku()
{
return $this->belongsTo('App\Skus', 'product_id', 'id');
}
}
class Skus extends Model
{
protected $table = 'skus';
public function products()
{
return $this->hasMany('App\Product', 'id', 'product_id');
}
}
您可以像这样用Eloquent获取数据
$keyword = 'some keyword'
Product::where('sku_prin', '=', $keyword) // for product table
->orWhereHas('sku', function($query) use ($keyword) {
$query->where('sku', '=', $keyword); // for sku table
});
甚至更多,使用单个字符串中的爆炸关键字进行模糊的whereLike查询
$keywordString = 'keyword1 keyword2';
$keywords = explode(' ', $keywordString);
Product::where(function($query) use ($keywords) { // for product table
foreach ($keywords as $keyword)
{
$query->orWhere('sku_prin', 'like', "%$keyword%");
}
})
->orWhereHas('sku', function($query) use ($keywords) { // for sku table
foreach ($keywords as $keyword)
{
$query->orWhere('sku', '=', $keyword);
}
});