先建立我們們所需要的檔案
//組別 model
php artisan make:model Models/Groups
//user和groups 關係model
php artisan make:model Models/UserGroups
修改Groups
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class 修改Groups extends Model
{
protected $table = 'groups';//表名
public $timestamps = false;
}
修改UserGroups
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class UserGroups extends Model
{
protected $table = 'user_groups';//表名
public $timestamps = false;
}
修改User
public function groups()
{
//關聯表 中間表名,當前表跟中間表對應的外來鍵,要關聯的表跟中間表對應的外來鍵
return $this->belongsToMany('App\Models\Groups','user_group','user_id','group_id');
}
然後在UserController進行呼叫
$data = User::find(1)->groups()->get();
$data = $this->Arr($data);