我有以下2张桌子:
表:产品
+----+---------+-------------+
| id | fn_id | created_at |
+----+---------+-------------+
| 1 | 4 | SOME TIME |
| 2 | 5 | SOME TIME |
| 3 | 6 | SOME TIME |
| 4 | 10 | SOME TIME |
| 5 | 10 | SOME TIME |
+----+---------+-------------+
表Fn
+----+---------+-------------+
| id | fn_id | created_at |
+----+---------+-------------+
| 1 | 10 | SOME TIME |
| 2 | 11 | SOME TIME |
| 3 | 12 | SOME TIME |
| 4 | 14 | SOME TIME |
+----+---------+-------------+
还有一个给我一个时间戳($ user_timestamp)的用户输入。
现在我需要获取所有产品,其中
products.fn_id is 10
fn.fn_id is 10
fn.created == $user_timestamp
产品模型具有以下关系:
public function fn() {
return $this->hasMany('App\FN', 'fn_id', 'fn_id');
}
现在,我已经尝试了多种方法,例如where查询,我想检查两者的fn_id是否为“ 10”,并且fn表的created_at值等于$ user_timestamp。
但是,我无法做到。
$products = Products::with('fn')->where('fn.fn_id', function ($query) use ($user_timestamp) {
$query->where([['fn_id', 10],['created_at', $user_timestamp]]);
})->get();
答案 0 :(得分:0)
您将不得不使用whereHas
来基于Products
约束fn
。
$products = Products::with('fn')->whereHas('fn', function($q) use($user_timestamp){
$q->where('fn_id', 10)->where('created_at', $user_timestamp);
})->get();
答案 1 :(得分:0)
尝试
$id_to_search=10;
$products = Products::with('fn')->where('fbn_id',$id_to_search)->whereHas('fn', function($q) use($user_timestamp,$id_to_search){
$q->where('fn_id', $id_to_search)->where('created_at', $user_timestamp);
})->get();