Định nghĩa Inverse của quan hệ One To Many (ok)
https://viblo.asia/p/eloquent-relationships-in-laravel-phan-1-PdbGnoEdeyA
Bây giờ chúng ta có thể truy cập tất cả các comments
, hãy định nghĩa một quan hệ để cho phép comments
có thể truy cập từ 1 post
. Để xác định các inverse của quan hệ hasMany
, chúng ta dùng phương thức belongsTo
:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
/**
* Get the post that owns the comment.
*/
public function post()
{
return $this->belongsTo('App\Post');
}
}
Một khi relationship được xác nghĩa, chúng ta có thể lấy Post
model cho một Comment
bằng cách truy cập post
"dynamic property":
$comment = App\Comment::find(1);
echo $comment->post->title;
Trong ví dụ trên, Eloquent sẽ cố gắng để match một post_id
từ Comment
model với 1 id của Post
model. Eloquent xác định mặc định tên foreign key bằng cách kiểm tra tên của phương thức relationship và nối với hậu tố _id
. Tuy nhiên bạn vẫn có thể tùy chỉnh nó bằng cách thêm đối số thứ 2 trong phương thức belongsTo
như sau:
/**
* Get the post that owns the comment.
*/
public function post()
{
return $this->belongsTo('App\Post', 'foreign_key');
}
Nếu model cha không sử dụng id
làm khóa chính của nó, bạn có thể tùy chọn nó bằng đối số thứ 3 của phương thức belongsTo
/**
* Get the post that owns the comment.
*/
public function post()
{
return $this->belongsTo('App\Post', 'foreign_key', 'other_key');
}
Last updated
Was this helpful?