如何在流明模型中声明复合主键?

时间:2019-05-09 12:12:53

标签: laravel lumen

我有一个带有三个主键的表,我正在尝试为其创建一个模型,并且我想使用find()函数,但是会引发错误:

代码:     

namespace App;

use Illuminate\Database\Eloquent\Model;

class Visit extends Model
{
  protected $table = 'ft_visit';

  protected $primaryKey = ['sk_time', 'sk_region', 'sk_device'];

  protected $fillable = [
      'sk_time', 'sk_region', 'sk_device', 'ds_page',
  ];

  public $timestamps = false;

  public function time()
  {
    return $this->belongsTo(Time::class, 'sk_time');
  }
}

错误:

(1/1) ErrorException
mb_strpos() expects parameter 1 to be string, array given

3 个答案:

答案 0 :(得分:2)

您可以尝试本文Solved: Eloquent doesn’t support composite primary keys.

中介绍的解决方案

在您的模型上添加以下$primaryKey方法,并删除<?php use Illuminate\Database\Eloquent\Builder; class Visit extends Model { public $incrementing = false; protected function setKeysForSaveQuery(Builder $query) { $query ->where('sk_time', '=', $this->getAttribute('sk_time')) ->where('sk_region', '=', $this->getAttribute('sk_region')); ->where('sk_device', '=', $this->getAttribute('sk_device')); return $query; } } 属性,您也许可以将这种不支持的功能添加到Eloquent模型中。

Working_abc
Working_cde
Working_efg
Working_mnc

编辑:如@Devon所述,这可能会以其他方式影响Eloquent,因此应在使用前 全面测试 。但是,如果您不在可以(最好)重组应用程序或数据的位置,这应该给您一些解决方法上的空白。

答案 1 :(得分:0)

不幸的是你不能。 Laravel和lumen(使用Eloquent)不支持复合键。

答案 2 :(得分:0)

口才不支持复合键。在这种情况下,要确保Eloquent兼容性,最好的做法是将现有的主组合键转换为唯一的组合键,并添加自动增量主键(id)以供Eloquent使用。