【问题标题】:Laravel - Get Data from Table where clause in other tableLaravel - 从表中获取数据 where 其他表中的子句
【发布时间】:2019-05-23 01:45:11
【问题描述】:

我有以下 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

products 模型有这样的关系:

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();

【问题讨论】:

    标签: laravel relation


    【解决方案1】:

    您必须使用whereHas 来约束基于fnProducts

    $products = Products::with('fn')->whereHas('fn', function($q) use($user_timestamp){
        $q->where('fn_id', 10)->where('created_at', $user_timestamp);
    })->get();
    

    【讨论】:

      【解决方案2】:

      试试这个

      $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();
      

      【讨论】:

        猜你喜欢
        • 2018-06-01
        • 1970-01-01
        • 2021-06-16
        • 2020-11-17
        • 1970-01-01
        • 1970-01-01
        • 2021-12-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多