One To Many (ok)
https://viblo.asia/p/eloquent-relationships-in-laravel-phan-1-PdbGnoEdeyA
One To Many
Một quan hệ one-to-many được sử dụng để xác định các mối quan hệ khi một model sở hữu nhiều số lượng của model khác. Ví dụ, 1 blog post có nhiều comment. Giống như nhiều Eloquent relationship khác, one-to-many được xác định bằng 1 function được đặt ở model của bạn:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
/**
* Get the comments for the blog post.
*/
public function comments()
{
return $this->hasMany('App\Comment');
}
}
Nhớ rằng, Eloquent sẽ tự động xác định đúng cột foreign key trên Comment
model. Theo quy ước, Eloquent sẽ có "snake case" tên của model và hậu tố _id
. Vì vậy, trong ví dụ này, Eloquent sẽ hiểu foreign key trên Comment
model chính là post_id
.
Một khi relationship được xác định, chúng ta có thể truy cập lấy collection của comments
bằng cách truy cập lấy comments property như sau:
$comments = App\Post::find(1)->comments;
Dĩ nhiên, vì tất cả các relationship cũng phục vụ query builder, bạn cũng có thể thêm các ràng buộc để comment được lấy ra và tiếp tục thêm các chuỗi query:
$comments = App\Post::find(1)->comments()->where('title', 'foo')->first();
Giống như hasOne
, bạn cũng có thể ghi đè các foreign key là local key bằng cách thêm các đối số cho phương thức hasMany
.
return $this->hasMany('App\Comment', 'foreign_key');
return $this->hasMany('App\Comment', 'foreign_key', 'local_key');
Last updated
Was this helpful?