Định nghĩa các Inverse của Relationship (ok)
https://viblo.asia/p/eloquent-relationships-in-laravel-phan-1-PdbGnoEdeyA
Định nghĩa các Inverse của Relationship
Vì vậy, chúng ta có thể truy cập vào Phone model từ User model. Bây giờ, chúng ta sẽ định nghĩa 1 relationship trên Phone model sẽ cho phép chúng ta truy cập vào User model. Chúng ta sử dụng phương thức nghịch đảo của hasOne là belongsTo:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Phone extends Model
{
/**
* Get the user that owns the phone.
*/
public function user()
{
return $this->belongsTo('App\User');
}
}Trong ví dụ trên, Phone model sẽ cố gắng để match cột user_id với 1 giá trị id ở User model. Tuy nhiền , nếu foreign key trên Phone model không phải là user_id, bạn có thể tùy chỉnh bằng cách thêm 1 đối số thứ 2 vào phương thức belongsTo như sau:
public function user()
{
return $this->belongsTo('App\User', 'foreign_key');
}Và cũng giống như phương thức hasOne, bạn có thể thêm vào đối số thứ 3 để thay đổi mặc định của phương thức là đối chiếu với cột id của User model như sau:
public function user()
{
return $this->belongsTo('App\User', 'foreign_key', 'other_key');
}Last updated
Was this helpful?