1use Illuminate\Database\Eloquent\Builder;
2
3// Retrieve posts with at least one comment containing words like code%...
4$posts = Post::whereHas('comments', function (Builder $query) {
5 $query->where('content', 'like', 'code%');
6})->get();
7
8// Retrieve posts with at least ten comments containing words like code%...
9$posts = Post::whereHas('comments', function (Builder $query) {
10 $query->where('content', 'like', 'code%');
11}, '>=', 10)->get();
1For example, a blog post may have an infinite number of comments. And a single
2comment belongs to only a single post
3
4class Post extends Model
5{
6 public function comments()
7 {
8 return $this->hasMany('App\Models\Comment');
9 }
10}
11
12class Comment extends Model
13{
14 public function post()
15 {
16 return $this->belongsTo('App\Models\Post');
17 }
18}
1//id for single
2$user->reasons->attach($reasonId);
3
4//array for multiple
5$user->reasons->attach($reasonIds);
6
7$user->save();
1$user = User::find(1);
2
3$user->roles()->detach([1, 2, 3]);
4
5$user->roles()->attach([
6 1 => ['expires' => $expires],
7 2 => ['expires' => $expires],
8]);