代码之家  ›  专栏  ›  技术社区  ›  Oliver Kucharzewski

使用非整数主键连接两个不起作用的模型之间的关系

  •  0
  • Oliver Kucharzewski  · 技术社区  · 8 年前

    我有两种型号: Holiday HolidayInfo . 如下所示:

    假日

    class Holiday extends Model
    {
        protected $table = 'holidays';
        protected $primaryKey = 'holiday_id';
        public $timestamps = false;
        public function dates(){
            return $this->hasOne('App\HolidayDates', 'holiday_id');
        }
        public function images(){
            return $this->hasMany('App\HolidayImages', 'holiday_id');
        }
        public function info(){
            return $this->hasOne('App\HolidayInfo', 'holiday_id');
        }
        public function pricing(){
            return $this->hasOne('App\HolidayPricing', 'holiday_id');
        }
    }
    

    HolidayInfo度假信息

    class HolidayInfo extends Model
    {
        protected $table = 'holiday_info';
        public $timestamps = false;
        protected $primaryKey = 'holiday_id';
        public function holiday(){
            return $this->hasOne('App\Holiday', 'holiday_id');
        }
    }
    

    我的桌子:

    enter image description here enter image description here

    如何在控制器中利用这些相互关联的模型,同时使用简单的where子句?换句话说,HolidayInfo和Holiday都有一些我需要的信息,但是以某种方式执行连接,然后执行where语句来缩小数据范围会更有效。

    这是我尝试过的,但它没有返回正确的数据:

    $holidays = Holidays::with('info')->get();
    

    这是返回的内容-如您所见,“info”返回为null。 enter image description here

    Holidays::where('country', $country)->with('info')->get();
    

    返回以下信息,表明尚未执行连接:

    SQLSTATE[42S22]: Column not found: 1054 Unknown column 'country' in 'where clause' (SQL: select * from holidays where country = australia)
    

    国家是“holiday_info”表的一部分。

    $holiday_info = Holidays::find(0)->info()->where('country', $country)->get();

    运行以下命令后,会出现60多个结果,因此SQL运行良好,而不是laravel:

    SELECT * from holidays JOIN holiday_info ON holidays.holiday_id = holiday_info.holiday_id
    

    如何将模型/关系及其数据结合起来,以便在一个地方使用?

    3 回复  |  直到 8 年前
        1
  •  2
  •   Vision Coderz    8 年前

    Yuo已经在假日模型中添加了关系

    public function info(){
            return $this->hasOne('App\HolidayInfo', 'holiday_id');
        }
    

    你可以使用 with

    Holiday::where(your condition)->with('info')->get();
    

    已更新

       public function info(){
            return $this->hasOne('App\HolidayInfo', 'holiday_id','holiday_id');
        }
    

    有一个关系

    hasOne($related, $foreignKey, $localKey )
    
        2
  •  0
  •   Oliver Kucharzewski    8 年前

    感谢@iCoders帮我破案。

    public $incrementing = false; 应该在假日模式中设置,因为它是非整数主键。

        3
  •  0
  •   parpar    8 年前

    只用雄辩就行了

    $holidays = Holiday::where(your condition)->with("info")->get();
    

    然后,在获取信息价值时,只需使用:

    foreach($holidays as $holiday){
        $holiday->info->youInfoFieldHere
    }