【问题标题】:four tables joins in laravel eloquent在 laravel eloquent 中连接四个表
【发布时间】:2016-05-19 06:41:24
【问题描述】:

这个查询是针对 codeigniter 如何在 laravel eloquent 中实现的

 $this->db->select('*');
            $this->db->from('countries cun'); 
            $this->db->join('cities cit', 'cit.country_code=cun.country_code', 'left');
            $this->db->join('city_states cits', 'cits.country_code=cun.country_code', 'left');
            $this->db->join('timezone timz', 'timz.country_code=cun.country_code', 'left');
            $this->db->where('cun.country',$id);         
           return $query = $this->db->get()->result();

【问题讨论】:

    标签: laravel


    【解决方案1】:

    试试这个

    return DB::table('countries AS cun')
        ->leftJoin('cities AS cit', 'cit.country_code', '=', 'cun.country_code')
        ->leftJoin('city_states AS cits', 'cits.country_code', '=', 'cun.country_code')
        ->leftJoin('timezone AS timz', 'timz.country_code', '=', 'cun.country_code')
        ->where('cun.country', $id)
        ->get(); 
    

    雄辩模型

    return Country::leftJoin('cities AS cit', 'cit.country_code', '=', 'countries.country_code')
         ->leftJoin('city_states AS cits', 'cits.country_code', '=', 'countries.country_code')
         ->leftJoin('timezone AS timz', 'timz.country_code', '=', 'countries.country_code')
         ->where('countries.country', $id)
         ->get();  
    

    【讨论】:

    • 我的问题是 eloquent 模型而不是查询构建器
    • 好的。我已经更新了答案。检查一下,如果这对您有帮助,请告诉我。
    【解决方案2】:

    See here

    Countries::with(["cities", "city_states", "timezone"])->where("country", $id)->get();

    Countries - Eloquent 模型。

    citiescity_statestimezone - relationshipsCountries 模型中。

    【讨论】:

      猜你喜欢
      • 2019-12-06
      • 2016-07-22
      • 1970-01-01
      • 2023-03-12
      • 2023-04-03
      • 2019-06-28
      • 2019-09-06
      • 1970-01-01
      • 2020-06-27
      相关资源
      最近更新 更多