简体   繁体   English

对 Laravel model 关系插入应用一些约束

[英]Apply some constraints on Laravel model relationship inserting

I tried to find some suggestions in the web, but I couldn't...我试图在 web 中找到一些建议,但我无法...

I would like to use some constraints in the save method for a relationship in Laravel, I'll do an example to explain it我想在Laravel中的关系的save方法中使用一些约束,我举个例子来解释一下

Let's suppose I've the 2 models Post and Comment , like in the Laravel documentation:假设我有 2 个模型PostComment ,就像在 Laravel 文档中一样:

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

and

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

Now, I would like to do a check on a new comment inserting, for example I would like to avoid the insertion if more than ten comments for that post already exist.现在,我想检查插入的新comment ,例如,如果该post评论已经存在十多个,我想避免插入。

I insert a new comment with these instructions我用这些说明插入一条新comment

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

I could check before these lines, but I would like to check in some other point, where all the saves are detected, is there something similar?我可以在这些行之前检查,但我想检查其他点,检测到所有保存,是否有类似的东西? Otherwise, is there some "standard way" to do it?否则,是否有一些“标准方法”来做到这一点?

There are helper methods in eloquent Model class that are exactly what you need. eloquent Model class 中的辅助方法正是您所需要的。 Since you need to do the check before inserting, you want to use the static::creating or static::saving method.由于您需要在插入前进行检查,因此您希望使用static::creatingstatic::saving方法。 Use saving if you want to validate both when creating and updating a comment.如果您想在创建和更新评论时同时验证,请使用saving In the Comment model add this:Comment model 中添加:

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.
    });
}

You can do it with count().您可以使用 count() 来完成。 Like beliw you can try.像下面你可以试试。 Where if the rows have less than 10 comments then it will save otherwise it will return back to the url.如果行的评论少于 10 条,则会保存,否则将返回 url。

$comment = new Comment();
If(count ($post->comments) <10){
$post->comments()->save($comment);
} 
else 
return back() ;//dont save return back;

Hope it will help希望它会有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM