การ JOIN ตารางใน Laravel 5.1



ใช้ Model ของ table นั้นๆ แล้วเพิ่ม relation function ใน model นั้นเช่น user -> user_profile
 สัมพันธ์กันแบบ 1- n
อาจจะ เขียน function

   ใน Model สร้างฟังก์ชั่นสำหรับ Relattion User.php

public function userProfile{
  return hasMany('UserProfile', 'profileID');
}

ใน Model ก็ต้องสร้าง Function เหมือนกันสำหรับ Relattion UserProfile.php

public function User{
  return belongTo('User', 'id');
}

การเรียกใช้ใน controller
$user_with_profile = User::where('id', '=', '1')->first()->with('UserProfile');


ก็จะได้ข้อมูล ของ Obj Model User แล้ Model UserProfile ออกมาโดยจะเป็นประมาณนี้

array(User)[
  id => 'x'
  x => 'xx'
  'xx' => 'xxx'
  'UserProfile' => [
    'profileID' => 'x',
    ....
  ]
]

เพิ่มเติมอ่านได้ในคู่มือ laravel 5.1 ได้เลยครับ : https://laravel.com/docs/5.1/eloquent-relationships

Related Posts