简体   繁体   中英

laravel relationship one to many multiple table

I have 3 tables.

Car  - Door - Fan

A car can have one or many doors. A door can have one or many fans.

Structure

Car - id | name

Door - id | car_id | side

Fan - id | door_id | color

my model is defined:

Car

   public class Car extends Eloquent{

    protected $table = "car";

     public function door()
    {
        $this->hasMany('Room');
    }

    } 

Door

   public class Door extends Eloquent{

    protected $table = "door";

   public function car()
    {
        $this->belongsTo('Car');
    }

   public function fan()
    {
        $this->hasMany('Fan');
     }

   } 

Fan

      public class Fan extends Eloquent{

      protected $table = "fan";
      public function door(){
        $this->belongsTo('Door');
      } 
    }

I am able to retrieve the doors related to car, but not the fans related to the door

This works fine, but when I try to retrieve the fan of the door it throws me an error

  $car = Car::find(1);
  foreach($car->door as $dr)
   {
     echo $dr->side;
   }

--

     Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation         
   $car  = Car::find(1);
   foreach($car->door as $dr)
   {
      echo $dr->size;
       foreach($dr->fan as $fn)
       {
          echo $color;
       }
   }

You need to add return for all relations, for example

public class Car extends Eloquent{

protected $table = "car";

    public function doors() // doors with 's' because many
    {
        return $this->hasMany('Door'); // Door for class not door
    }

}

And use eager loading to alleviate the N + 1 query

This line in the Fan model

$this->belongsTo('door');

needs an exact spelling of the parent model, so it should be

$this->belongsTo('Door');

with a capital 'D'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM