Model - Eloquent 關聯

Eloquent 關聯

一對一

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    public function profile()
    {
        return $this->hasOne('App\Profile');
        // return $this->hasOne('App\Profile', 'foreign_key', 'profile_key');
    }
}
$profile = User::find(1)->profile;
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Profile extends Model
{
    public function user()
    {
        // 應被放置在...
        return $this->belongsTo('App\User');
    }
}

使用 Eloquent 的動態屬性來取得關聯紀錄

$profile = User::find(1)->profile;

一對多

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Profile extends Model
{
    public function phones()
    {
        return $this->hasMany('App\Phone');
        // return $this->hasMany('App\Phone', 'foreign_key', 'phone_key');
    }
}
$phones = App\Profile::find(1)->phones;

foreach ($phones as $phone) {

}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Phone extends Model
{
    public function profile()
    {
        return $this->belongsTo('App\Profile');
    }
}
$phones = App\Profile::find(1)->phones()->first();

多對多

User

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    public function roles()
    {
        return $this->belongsToMany('App\Role');
        // return $this->belongsToMany('App\Role', 'user_roles');
        // return $this->belongsToMany('App\Role', 'user_roles', 'user_id', 'role_id');
    }
}
$user = App\User::find(1);

foreach ($user->roles as $role) {

}
$roles = App\User::find(1)->roles()->orderBy('name')->get();

Role

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    public function users()
    {
        return $this->belongsToMany('App\User');
    }
}
return $this->belongsToMany('App\Role')->withTimestamps();

關聯查詢

$user->posts()->where('active', 1)->get();

results for ""

    No results matching ""