journelink/resolvable

使Eloquent模型可以通过除主键以外的字段进行解析

1.0.1 2018-07-07 20:46 UTC

This package is auto-updated.

Last update: 2024-09-04 21:19:25 UTC


README

使你的Eloquent模型可以通过其键以外的更多字段进行解析。

模型将从同一模型的实例、主键或$resolvable变量中指定的任何字段进行解析。

这避免了在查找正确的模型时需要列出多个where()语句,或者当数据参数可以变化时。

用法

将Resolvable特质导入你的模型并定义你的可解析字段。(在解析过程中,你的模型上的主键字段将自动包含在内)

<?php

namespace App\Models;

use JournoLink\Resolvable\Resolvable;
use Illuminate\Database\Eloquent\Model;

class Thing extends Model
{
    use Resolvable;

    /**
     * An array of field names that the Model can be resolved from
     *
     * @var array
     */
    protected $resolvable = ['name'];
    ...
}

调用resolve()静态方法,从你的参数中解析实例。

// Thing {
//     id: 1
//     name: "My Thing"
//     value: 123.45
// }

// All 3 will return the same Model
$thing1 = Thing::resolve(1);
$thing2 = Thing::resolve('My Thing');
$thing3 = Thing::resolve($thing1);

// This will return null as "value" isn't in the $resolvable array
$thing4 = Thing::resolve(123.45);