Php 对Laravel模型关系插入应用一些约束

Php 对Laravel模型关系插入应用一些约束,php,laravel,eloquent,eloquent-relationship,Php,Laravel,Eloquent,Eloquent Relationship,我试图在网上找到一些建议,但我无法 我想对Laravel中的关系使用save方法中的一些约束,我将用一个例子来解释它 让我们假设我有两个模型Post和Comment,就像在Laravel文档中一样: class Post extends Model { public function comments() { return $this->hasMany('App\Comment'); } } 及 现在,我想检查一个新的评论插入,例如,如果该帖子已经

我试图在网上找到一些建议,但我无法

我想对Laravel中的关系使用
save
方法中的一些约束,我将用一个例子来解释它

让我们假设我有两个模型
Post
Comment
,就像在Laravel文档中一样:

class Post extends Model
{
    public function comments()
    {
        return $this->hasMany('App\Comment');
    }
}

现在,我想检查一个新的
评论
插入,例如,如果该
帖子
已经存在十多条评论,我想避免插入

我根据这些说明插入新的
注释

$comment = new Comment();
$post->comments()->save($comment);

我可以在这些行之前进行检查,但我想在其他点进行检查,在这些点上检测到所有保存,是否存在类似的情况?否则,是否有一些“标准方法”可以做到这一点?

在雄辩的
Model
类中有一些辅助方法正是您所需要的。由于插入前需要进行检查,因此需要使用
static::creating
static::saving
方法。如果要在创建和更新注释时同时验证,请使用
保存
。在
注释
模型中添加以下内容:

protected static function boot()
{
    parent::boot();

    static::creating(function (Comment $comment) {
        // Do validation on the $comment model.
        // Feel free to make sql queries or do anything you need.
        // Throw an exception if your validation fails.
    });
}

在雄辩的
Model
类中有一些辅助方法正是您所需要的。由于插入前需要进行检查,因此需要使用
static::creating
static::saving
方法。如果要在创建和更新注释时同时验证,请使用
保存
。在
注释
模型中添加以下内容:

protected static function boot()
{
    parent::boot();

    static::creating(function (Comment $comment) {
        // Do validation on the $comment model.
        // Feel free to make sql queries or do anything you need.
        // Throw an exception if your validation fails.
    });
}
您可以使用count()完成此操作。相信你可以试试。其中,如果行的注释少于10条,则将保存,否则将返回url

$comment = new Comment();
If(count ($post->comments) <10){
$post->comments()->save($comment);
} 
else 
return back() ;//dont save return back;
$comment=newcomment();
If(count($post->comments)comments()->save($comment);
} 
其他的
return back();//不保存return back;
希望对您有所帮助

您可以使用count()进行操作。您也可以尝试。如果行的注释少于10条,则将保存,否则将返回url

$comment = new Comment();
If(count ($post->comments) <10){
$post->comments()->save($comment);
} 
else 
return back() ;//dont save return back;
$comment=newcomment();
If(count($post->comments)comments()->save($comment);
} 
其他的
return back();//不保存return back;
希望它能帮助你理解“新评论”的含义?因为当你向收藏中插入一个新项目时,它可以是相同的。如果你想更新一个收藏,那么它就不同了。你理解“新评论”的含义是什么?因为当你向收藏中插入一个新项目时,它可以是相同的。如果你想更新一个收藏,那么它就不同了。