Page 47 - Laravel5_v1
P. 47

<?php

                 namespace App;

                 use Illuminate\Database\Eloquent\Model;

                 class TypeBooks extends Model
                 {
                     protected $table = 'typebooks';

                     public function books() {
                                                                                      ์
                                                                          ํ
                                                                                       ู
                         return $this->hasMany(Books::class); //กาหนดความสัมพันธรปแบบ One To Many ไปยังตาราง
                 books
                     }
                 }


                                                               ้
                 เปดไฟล์ app\Books.php เพื อทําการ inverse relation โดยใช
                  ิ


                 <?php

                 namespace App;

                 use Illuminate\Database\Eloquent\Model;

                 class Books extends Model
                 {
                    protected $table = 'books';
                    protected $fillable = ['title','price','typebooks_id'];

                    public function typebooks() {
                                                                                                               ้
                                                                                                      ํ
                          return $this->belongsTo(TypeBooks::class, 'typebooks_id'); //กาหนด FK ดวย
                    }
                 }

                                                                                        ้
                                                                                          ้
                                                                                                              ้
                                                                                                      ์
                                                                                            ้
             3.  สรางไฟล์ BooksController.php ในรปแบบของ resource หรอเรยกว่า RESTful Controller กได ใหเขาไปโฟลเดอรโปรเจค แลว
                  ้
                                                              ื
                                            ู
                                                                 ี
                                                                                      ็
                  ิ
                 เปด Composer ขึ นมา พิมพ์คําสั ง php artisan make:controller BooksController –resource แลวกด enter
                                                                                          ้
   42   43   44   45   46   47   48   49   50   51   52