php - Laravel HasManyThrough 关系空输出

标签 php mysql laravel eloquent

我需要有关 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/

相关文章:

php - 不使用自动递增 ID 时使用 Propel ORM 获取插入行的 ID

php - Laravel 中的一对一关系总是需要 first() 吗?

mysql - 大表查询优化(mysql)

mysql - SQL - 通过不同的条件聚合相同的列

php - 我正在使用 fputcsv() 创建一个 .csv 文件,我想在 PHPMailer 中使用 AddAttachment() 来自动发送它

php - 在 Wamp 服务器上为 Z​​end 应用程序设置 VirtualHost

mysql - 在mysql查询中结合Not In和like函数

reactjs - 带有水果蛋糕的 Laravel CORS

php - Laravel 5.2 Auth 总是重定向到登录页面(可能 session 不持久)

mysql - 仅包含某些列的 Laravel 模型查询