首页 > 解决方案 > 如何在 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

标签: laravellumen

解决方案


您可以尝试本文中提出的解决方案 已解决:Eloquent 不支持复合主键。

在您的模型上添加setKeysForSaveQuery下面的方法并删除该$primaryKey属性,您也许可以将这个原本不受支持的功能添加到您的 Eloquent 模型中。

<?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;
    }

}

编辑:正如@Devon 所指出的,这可能会以其他方式影响 Eloquent,应在使用前彻底测试。但是,如果您不处于可以(最好)重构应用程序或数据的位置,这应该会给您一些解决问题的方法。


推荐阅读