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
解决方案
您可以尝试本文中提出的解决方案 已解决: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,应在使用前彻底测试。但是,如果您不处于可以(最好)重构应用程序或数据的位置,这应该会给您一些解决问题的方法。
推荐阅读
- java - 是什么让三端队列的 Java 链表实现变慢了?
- ruby - 处理除 Ruby 中的一种错误之外的所有类型的错误?
- rest - Spring数据休息:页面和规范休息API不返回任何数据
- javascript - var_dump 发布后不显示任何内容
- yaml - gatsby-transformer-remark 的自定义 YAML 类型
- xamarin - 从 Xamarin 表单页面替换内容页面
- selenium - 如何通过 RemoteWebDriver 使用 Selenium TouchActions
- python - Aiohttp 干净的架构。交易等
- python - 如果字符串没有空格,则从字符串中获取特定单词
- swift - 如何为同一个标签栏项目显示不同的视图页面?