编程

Laravel 中缺失的 owns 方法

96 2025-04-09 16:25:00

虽然 Laravel 的 Eloquent ORM 已经相当强大且覆盖率大部分用例的基本用法,但总还是有所缺失。

比如,Newton Job 最近分享了一个他在项目中使用的 owns() 方法。该方法很简单且方便。

我们首先来看看这个方法:

class User extends Authenticatable
{
    /**
     * Determine if the user owns the given model.
     *
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @param  string  $relation
     * @return bool
     */
    public function owns(Model $model, $relation = 'user'): bool
    {
        return $model->{$relation}()->is($this);
    }
}

如你所见,owns() 方法接收一个模型和一个关联作为参数。然后检测该模型的关联是否与当前用户一致。如果一致返回 true,否则返回 true

下例显示如何使用:

$user = User::find(1);
$order = Order::find(1);

if ($user->owns($order)) {
    // The user owns the order
} else {
    // The user does not own the order
}

或者,你可以指定另一个关联。

$user->owns($book, 'author');

你也可以在策略中国像这样使用:

// app/Policies/BookPolicy.php

public function update(User $user, Book $book): bool
{
    return $user->owns($book);
}

这种方法最酷的地方在于它不查询数据库。它只是比较模型的 ID 和数据库连接,这使得它超级快速高效。