laravel has many code example
Example 1: laravel has many
public function comments()
{
return $this->hasMany(Comment::class);
}
Example 2: has many through laravel
class Country extends Model
{
public function posts()
{
return $this->hasManyThrough(
'App\Post',
'App\User',
'country_id',
'user_id',
'id',
'id'
);
}
}
when
countries
id - integer
name - string
users
id - integer
country_id - integer
name - string
posts
id - integer
user_id - integer
title - string
Example 3: one to many laravel
For example, a blog post may have an infinite number of comments. And a single
comment belongs to only a single post
class Post extends Model
{
public function comments()
{
return $this->hasMany('App\Models\Comment');
}
}
class Comment extends Model
{
public function post()
{
return $this->belongsTo('App\Models\Post');
}
}
Example 4: laravel detach
$user->roles()->detach($roleId);
$user->roles()->detach();
Example 5: laravel has many
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function comments()
{
return $this->hasMany('App\Models\Comment');
}
}
Example 6: laravel how to query belongsTo relationship
$movies = Movie::whereHas('director', function($q) {
$q->where('name', 'great');
})->get();