简体   繁体   中英

the relation is not appending to the model in laravel

i want to append a relation to my model in laravel i know its possible with resource but i need it to be appened to model so here its like below what i do:

 protected $appends = ['accommodation_rooms'];
    public function getAccommodationRoomsAttribute(){
        return $this->accommodationRooms();
    }

and my relation is:

 public function accommodationRooms()
    {
        return $this->Hasmany(AccommodationRoom::class);
    }

but when i run my api it returns null but when i call the relation it has the relation and it has no problem. any idea what i am doing wrong??

EDIT

  $data = Accommodation::with('city', 'accommodationFacilities', 'gallery')
            ->where('is_deleted', 0)->Paginate(env('PAGINATE_NUMBER'));
        return $data;

return $this->accommodationRooms() will return an instance of query builder. That is probably why it was showing empty.

Change it to

public function getAccommodationRoomsAttribute(){
    return $this->accommodationRooms;
}

Call it without ()

public function getAccommodationRoomsAttribute(){
    return $this->accommodation_rooms;
}

And update your relation to:

 public function accommodationRooms()
    {
        return $this->hasMany(AccommodationRoom::class);
    }

And make sure you have accommodation_id column in your accommodation_rooms table

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