laravel hasmanythrough code example
Example 1: 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 2: laravel has one through
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Mechanic extends Model
{
public function carOwner()
{
return $this->hasOneThrough('App\Owner', 'App\Car');
}
}
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 eloquent associate
$account = App\Account::find(10);
$user->account()->associate($account);
$user->save();