· 9 years ago · Oct 20, 2016, 02:58 AM
1// Route
2
3Route::get('/test', 'RelationshipController@test');
4
5
6// Controller
7
8class RelationshipController extends Controller
9{
10 public function test()
11 {
12 // dd(A::all());
13 // dd(A::with('b')->get());
14 dd(A::with('b.c')->get());
15 }
16}
17
18
19// A.php
20
21class A extends Model
22{
23 /**
24 * @var string
25 */
26 protected $table = 'a';
27
28 /**
29 * @return \Illuminate\Database\Eloquent\Relations\hasOne
30 */
31 public function b()
32 {
33 return $this->hasOne(B::class, 'id', 'b_id');
34 }
35}
36
37
38// B.php
39
40class B extends Model
41{
42 /**
43 * @var string
44 */
45 protected $table = 'b';
46
47 /**
48 * @return \Illuminate\Database\Eloquent\Relations\hasOne
49 */
50 public function c()
51 {
52 return $this->hasOne(C::class, 'id', 'c_id');
53 }
54}
55
56
57// C.php
58
59class C extends Model
60{
61 /**
62 * @var string
63 */
64 protected $table = 'c';
65}
66
67
68// DB dump
69
70-- Table structure for table `a`
71
72CREATE TABLE `a` (
73 `id` int(11) NOT NULL,
74 `name` varchar(45) DEFAULT NULL,
75 `b_id` int(11) DEFAULT NULL,
76 PRIMARY KEY (`id`)
77) ENGINE=InnoDB DEFAULT CHARSET=utf8;
78
79
80-- Table structure for table `b`
81
82CREATE TABLE `b` (
83 `id` int(11) NOT NULL,
84 `name` varchar(45) DEFAULT NULL,
85 `c_id` int(11) DEFAULT NULL,
86 PRIMARY KEY (`id`)
87) ENGINE=InnoDB DEFAULT CHARSET=utf8;
88
89-- Table structure for table `c`
90
91DROP TABLE IF EXISTS `c`;
92
93CREATE TABLE `c` (
94 `id` int(11) NOT NULL,
95 `name` varchar(45) DEFAULT NULL,
96 PRIMARY KEY (`id`)
97) ENGINE=InnoDB DEFAULT CHARSET=utf8;