mistery23/eloquent-composite-primary-keys

此包已被废弃且不再维护。未建议替代包。

在 Eloquent 模型上提供复合主键

1.0.8 2019-12-05 11:06 UTC

This package is auto-updated.

Last update: 2020-11-05 13:27:12 UTC


README

一个特质,用于在您的 Eloquent 模型中实现以支持复合主键。Laravel Schema 构建器支持创建复合主键,但 Eloquent 模型不支持。

此包主要受 Stack Exchange 上建议的代码的启发,并且已作为一个具有更多功能的包发布。我需要一个单独的包来仅为此目的。

重要:现在为只读

我已决定使此项目为只读,不再进一步工作。在 Laravel 中这样做会有许多与性能相关的问题,这使得它不再有趣且不值得我投入精力。

如果您仍然想在 Laravel 中使用此功能,可以查看包含类似功能的LaravelTreats 包

安装

通过 Composer 安装此包

composer require mistery23/eloquent-composite-primary-keys

请确保您有一个支持复合主键的数据库模式,例如通过迁移

Schema::create('products', function (Blueprint $table) {
    $table->integer('first_key');
    $table->integer('another_key');
    $table->primary(['first_key', 'another_key']);
    $table->timestamps();
});

在您希望具有复合主键的 Eloquent 模型上使用此特质

namespace App;

use Illuminate\Database\Eloquent\Model;
use Mistery23\EloquentCompositePrimaryKeys\HasCompositePrimaryKey;

class Product extends Model
{
	use HasCompositePrimaryKey;

接下来,您将 Eloquent 模型上的 $primaryKey 属性设置为一个数组,该数组包含组成复合主键的字段名称

protected $primaryKey = ['first_key', 'another_key'];