Laravel 关系查找 UUID

Laravel Relationship Find UUID

我已经为 UUID 创建了一个 Trait。我在我的代码中使用了很多 relationschip。在一段关系中,你可以做 find()findOrFail(),但我已经为 findU()findUOrFail() 编写了代码,但我不能在一段关系中使用它。我该如何解决?

特质:

<?php

namespace App\Modules\Base\Traits;

use Ramsey\Uuid\Uuid;

/**
 * Trait Uuids
 *
 * @package Modules\Core\Traits
 */
trait Uuids
{
    /**
     * Boot function from laravel.
     */
    public static function bootUuids ()
    {
        static::creating(function ($model) {
            $model->uuid = Uuid::uuid4()->toString();
        });
    }

    /**
     * @param $uuid
     *
     * @return mixed
     */
    public static function findU ($uuid)
    {
        return static::where('uuid', '=', $uuid)->first();
    }

    /**
     * @param $uuid
     *
     * @return mixed
     */
    public static function findUOrFail($uuid)
    {
        $post = static::where('uuid', '=', $uuid)->first();

        if( is_null($post) ) {
            return abort(404);
        } else {
            return $post;
        }
    }

}

控制器:

/**
     * Show
     */
    public function show(Request $request, $uuid)
    {
        return responder()->success($request->user()->projects()->findUOrFail($uuid))->respond();
    }

错误: Call to undefined method Illuminate\Database\Eloquent\Relations\BelongsToMany::findUOrFail()

在模型中直接引用函数应该会有所帮助,而不是尝试在特征中直接访问它。我假设您在项目模型中包含了上面的 Uuids 特征。如果是这样,请尝试在项目模型上创建一个方法,如下所示:

public function tryFindUOrFail($uuid)
{
    return $this->findUOrFail($uuid);
}

然后你会把你的显示方法写成:

return responder()->success($request->user()->projects()->tryFindUOrFail($uuid))->respond();

如果这不起作用,您可能需要将您的方法包含在 $appends 数组中,以便可以通过关系直接访问它。

假设您不需要 id 因为您正在使用 uuid

在您的迁移文件中,您需要:

$table->uuid('uuid');
$table->primary('uuid');

在您的模型中:

use Uuids;
protected $primaryKey = 'uuid';
public $incrementing = false;

或者更简单

在您的迁移文件中:

$table->uuid('id');
$table->primary('id');

在您的模型中:

use Uuids;
public $incrementing = false;

您不需要覆盖 findOrFailfind