在 Laravel 中将模型关联到属于关系时启用类型检查

问题描述 投票:0回答:1

假设我有三个模型

User
Post
Comment
并像这样链接:

class User extends Model
{
    public function posts(): HasMany
    {
        return $this->hasMany(Post::class);
    }
}
class Comment extends Model
{
    public function post(): BelongsTo
    {
        return $this->belongsTo(Post::class);
    }
}
class Post extends Model
{
    /**
     * Get the comments for the blog post.
     */
    public function comments(): HasMany
    {
        return $this->hasMany(Comment::class);
    }
}

我想关联一个帖子来发表评论,我会这样做:


$comment->post()->associate($post);

但是如果我错误地将不同的模型传递给关联函数:

$comment->post()->associate($user);

那么它仍然可以工作,它会关联与传递的用户具有相同id的帖子,这是错误的。

基本上,关联函数不会检查关联之前传递的模型的类型,是否可以启用某些功能,以便 laravel 在关联之前检查模型的类型?

php laravel relationship belongs-to
1个回答
0
投票

associate
方法不检查类型,也不进行参数类型提示,它需要一个 Model 实例、字符串、int 或 null,如下所示:

/**
 * Associate the model instance to the given parent.
 *
 * @param  \Illuminate\Database\Eloquent\Model|int|string|null  $model
 * @return \Illuminate\Database\Eloquent\Model
 */
public function associate($model)

基本上,您必须自己处理这个问题,因为这不是用户输入,因此很容易确保您传递了正确的参数。

否则,你将需要做多余的工作 -IMO- 来处理这个问题。

首先,您将重写模型中的

belongsTo
方法,该方法返回新的
BelongsTo
类(在下一步中)。
其次,您需要创建 BelongsTo 关注点的
shadow
版本,很可能您将继承
Illuminate\Database\Eloquent\Relations\BelongsTo
并重写
associate
方法来键入提示您的参数,给它一个正确的名称,比如说
 CommentsBelongsTo
什么的。

最后一堂课会是这样的:

use Illuminate\Database\Eloquent\Relations\BelongsTo;
use App\Models\Post;

class CommentsBelongsTo extends BelongsTo
{
    ...
    public function associate(Post $model)
    ...
}
© www.soinside.com 2019 - 2024. All rights reserved.