【问题标题】:Laravel HasManyThrough relation empty outputLaravel HasManyThrough 关系空输出
【发布时间】:2017-01-11 16:02:24
【问题描述】:

我需要 Laravel 雄辩的模型关系方面的帮助。我有三张桌子

项目

item_id
slideshowID

幻灯片

slideshow_id

图片

image_id
slideshowID

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

项目模型

public function images(){   
    return $this->hasManyThrough(
        'App\image','App\slideshow','slideshow_id','slideshowID','slideshowID'
    );}

控制器

$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' 但没有改变任何事情

【问题讨论】:

  • 我也试过 $this->belongsToMany 也得到了空数组,我做错了什么?

标签: php mysql laravel eloquent


【解决方案1】:

你很接近只需要改变一点像这个slideshows模型你需要在那里添加主键

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 它正在调用

【讨论】:

  • 嘿!感谢您的回答,我确实认为我在幻灯片模型中这样做了,但也许我出于某种原因评论了 /* */ 它,我现在在家,明天我会尝试并报告。谢谢!
  • 我在项目、幻灯片模型中添加了受保护的 $primaryKey,我确实在输出时获得了图像,但我得到了错误的图像。见编辑
【解决方案2】:

我解决了。我的数据库表设置错误。相反,如果有这样的表:

项目

item_id
slideshowID

幻灯片

slideshow_id

图片

image_id
slideshowID

我把它们改成

项目

item_id

幻灯片

slideshow_id
item_id

图片

image_id
slideshowID

【讨论】:

    猜你喜欢
    • 2016-01-22
    • 2018-10-18
    • 2023-03-09
    • 2018-07-24
    • 2020-10-14
    • 1970-01-01
    • 1970-01-01
    • 2018-03-08
    • 2021-12-06
    相关资源
    最近更新 更多