use*_*752 15 php mysql laravel laravel-5 laravel-eloquent
产品型号
public function country() {
return $this->hasMany('App\Models\ProductCountry', 'product_id', 'id');
}
Run Code Online (Sandbox Code Playgroud)
控制器
$product = Product::where('mall_' . $this->mall_id, '=', 1)
->whereHas('country', function ($i) use ($me) {
return $i->where('country_id', $me->country_id);
})
->find($key);
Run Code Online (Sandbox Code Playgroud)
原始SQL:
select * from `product` where `mall_3` = '1' and exists (select * from `product_country` where `product_country`.`product_id` = `product`.`id` and `country_id` = '109') and `product`.`id` = '3' and `product`.`deleted_at` is null limit 1
Run Code Online (Sandbox Code Playgroud)
上面的SQL返回没有结果(当产品id = 3时
在SQL下面返回正确的结果(当产品id = 6时)
select * from `product` where `mall_3` = '1' and exists (select * from `product_country` where `product_country`.`product_id` = `product`.`id` and `country_id` = '109') and `product`.`id` = '6' and `product`.`deleted_at` is null limit 1
Run Code Online (Sandbox Code Playgroud)
不知道,查询看起来没问题
以前的项目我也得到了这个问题,最后我再次使用find和循环而不是使用whereHas,但这次我再次遇到这个问题,并试图找出原因,但浪费了几个小时,仍然没有线索,下面是一个解决方法(忽略错误?)
$products = array();
foreach ($request->get('quantity') as $key => $var) {
if ($var > 0) {
$product = Product::with(['country'])->where('mall_' . $this->mall_id, '=', 1)
->find($key);
foreach ($product->country as $c) {
if ($c->country_id == $me->country_id && !isset($products[$product->id])) {
//Do something here...
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
我创建了上面提到的表(给出完全相同的关系、表名、模型名)并尝试了你的代码(通过给出硬编码值)
public function try1(){
$me = 109;
$key = 3;
$product = Product::where('mall_3' , '=', 1)
->whereHas('country', function ($i) use ($me) {
return $i->where('country_id', $me);
})
->find($key);
return $product;
}
public function try2(){
$me = 109;
$key = 6;
$product = Product::where('mall_3' , '=', 1)
->whereHas('country', function ($i) use ($me) {
return $i->where('country_id', $me);
})
->find($key);
return $product;
}
Run Code Online (Sandbox Code Playgroud)
但得到了完美的结果
{"id":3,"mall_1":1,"mall_2":1,"mall_3":1}
Run Code Online (Sandbox Code Playgroud)
和
{"id":6,"mall_1":1,"mall_2":1,"mall_3":1}
Run Code Online (Sandbox Code Playgroud)
请检查您的数据库是否一切正常,检查是否每个主键和外键都创建为“整数”。并检查数据库和表的“整理”。
首先要做的事情是:
如果您使用eloquent
(查找方法),您可以执行以下操作:
Product::find($id);
Run Code Online (Sandbox Code Playgroud)
它会返回一个产品模型,其中您提供的 id 等于主键。话虽如此,没有必要使用 a,whereHas()
因为它没有任何效果。find()
您可以尝试get()
或例如,而不是first()
,具体取决于您要寻找的内容。
如果您想打印出您的查询,您可以以结尾->toSql();
,它将把查询打印为字符串(有很大帮助!)。
我没有太注意目标,但我确定您是否使用
dd(Product::where('mall_' . $this->mall_id, '=', 1)
->whereHas('country', function ($i) use ($me) {
return $i->where('country_id', $me->country_id);
})
->toSql());
Run Code Online (Sandbox Code Playgroud)
您将能够比较您正在做的事情(因为您知道正确的结果或查询应该是什么样的)并能够弄清楚。
毕竟,我们确实需要锻炼来探索我们的思想!
归档时间: |
|
查看次数: |
903 次 |
最近记录: |