I need help with Laravel eloquent model relations. I have three tables :
items
item_id
slideshowID
slideshows
slideshow_id
images
image_id
slideshowID
I spent all day trying to get it to work, I just can't. What I want is, for each item to have its own slideshow of images.
item model
public function images(){
return $this->hasManyThrough(
'App\image','App\slideshow','slideshow_id','slideshowID','slideshowID'
);}
controller
$items=item::with('images')->get();
return \View::make('home')->with('items', $items);
View
@foreach($items as $item)
<div class='item' data-categoryid='{{$item->categoryID}}'>
<div class='item-image'>
@foreach($item->images as $image)
<img src='{{URL::asset($image->path)}}' data-image-id='{{$image->image_id}}' style='display:none'>
@endforeach
</div>
<div class='item-name'>{{$item->name}}</div>
<div class='item-price'>Od {{$item->price}}€</div>
<button class='btn-blue'>Več...</button>
</div>
@endforeach
Query
select `images`.*, `slideshows`.`slideshow_id` from `images` inner join `slideshows` on `slideshows`.`slideshow_id` = `images`.`slideshowID` where `slideshows`.`slideshow_id` in (?, ?, ?, ?, ?, ?, ?)" array(7) { [0]=> int(1) [1]=> int(7) [2]=> int(2) [3]=> int(6) [4]=> int(3) [5]=> int(4) [6]=> int(5) }
Output - empty images array
{"items_id":1,"code":"999","name":"koledar","description":"","slideshowID":1,"stock":999,"price":5.5,"categoryID":2,"images":[]}
EDIT I managed to get some images out, but they are wrong ones.
Item: 3
Slideshow fk:2
Slideshow id:3
9 images/bon2.jpg
Slideshow id:3
10 images/bon.jpg
It always gets the slideshow equal to item's ID. I have tried to add to item model protected $foreignKey='slideshowID' but doesn't change a thing
You are very close just need to change a little bit like this slideshows
model you need to add the primary key there
protected $primaryKey = 'slideshow_id';//https://github.com/laravel/framework/blob/5.3/src/Illuminate/Database/Eloquent/Model.php#L56
This is needed because when you are calling hasManyThrough
see here https://github.com/laravel/framework/blob/5.3/src/Illuminate/Database/Eloquent/Model.php#L875-L886 it's calling
I solved it. I had the database tables set up wrong. Instead if having tables like this:
items
item_id
slideshowID
slideshows
slideshow_id
images
image_id
slideshowID
I changed them to
items
item_id
slideshows
slideshow_id
item_id
images
image_id
slideshowID
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.