gpt4 book ai didi

php - Laravel HasManyThrough 关系空输出

转载 作者:行者123 更新时间:2023-11-29 19:35:46 26 4
gpt4 key购买 nike

我需要有关 Laravel Eloquent 模型关系的帮助。我有三张 table :

项目

item_id
slideshowID

幻灯片

slideshow_id

图像

image_id
slideshowID

我花了一整天的时间试图让它工作,但我就是做不到。我想要的是,每个项目都有自己的图像幻灯片。

商品模型

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);

查看

    @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}}&euro;</div>
<button class='btn-blue'>Več...</button>
</div>
@endforeach

查询

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) }

输出 - 空图像数组

{"items_id":1,"code":"999","name":"koledar","description":"","slideshowID":1,"stock":999,"price":5.5,"categoryID":2,"images":[]}

编辑我设法取出一些图像,但它们是错误的。

Item: 3
Slideshow fk:2
Slideshow id:3
9 images/bon2.jpg
Slideshow id:3
10 images/bon.jpg

它总是获取等于项目 ID 的幻灯片。我尝试添加到项目模型 protected $foreignKey='slideshowID' 但没有改变任何事情

最佳答案

你已经非常接近了,只需要稍微改变一下幻灯片模型,你需要在那里添加主键

protected $primaryKey = 'slideshow_id';//https://github.com/laravel/framework/blob/5.3/src/Illuminate/Database/Eloquent/Model.php#L56

这是必需的,因为当您调用 hasManyThrough 时,请参阅此处 https://github.com/laravel/framework/blob/5.3/src/Illuminate/Database/Eloquent/Model.php#L875-L886它在召唤

关于php - Laravel HasManyThrough 关系空输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41570007/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com