为了账号安全,请及时绑定邮箱和手机立即绑定

未定义的属性:stdClass::$images

未定义的属性:stdClass::$images

PHP
慕工程0101907 2021-09-18 13:52:21
在产品表中,我有图像行,它存储每个产品的图像,["4.jpg","5.jpg"]在每个产品的数据库中看起来像这样。现在我想在视图中显示产品和属于该产品的图像但卡住了它显示错误Undefined property: stdClass::$images我该如何解决?这里是代码刀片视图   @foreach($products as $product)   @foreach($product->images as $image)      <img src="{{url('images',$image->filepath)}}" alt="">     @endforeach     @endforeach控制器public function store(Request $request) { $Input=$request->all();$image=array();if($files=$request->file('image')){    foreach($files as $file){        $name=$file->getClientOriginalName();        $file->move('images',$name);        $image[]=$name;    }}  product::create(array_merge($Input, ['image' => json_encode($image),])); return redirect()->back(); }任何帮助都将得到认可。
查看完整描述

2 回答

?
jeck猫

TA贡献1909条经验 获得超7个赞

对于您遇到的错误,我认为这是因为您的产品表具有image作为属性,并且您正尝试使用images作为键来检索图像。


通过将图像存储为数组,您正在为您的应用程序实现一个糟糕的设计。


由于您有多个图像,因此创建了一个images以 product_id 作为外键的新表。


Schema::create('images', function (Blueprint $table) {

            $table->bigIncrements('id');

            $table->string('name');

            $table->dateTime('created_at');

            $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');

        });

现在,在您的产品和图像模式上添加关系。


/* add this on your Product.php modal */

public function images()

{

  return $this->hasMany('App\Image');

}

/* add this on your Image.php modal */

public function product()

{

   return $this->belongsTo('App\Product');

}

现在,要检索与某个产品相关的所有图像,您只需要调用


@foreach($product->images() as $image)

      <img src="{{url('images',$image->filepath)}}" alt="">

@endforeach


查看完整回答
反对 回复 2021-09-18
?
不负相思意

TA贡献1777条经验 获得超10个赞

在控制器中,您将其保存在image

'image' => json_encode($image),

但在您阅读的视图中images

@foreach($product->images as $image)

所以我猜应该是$product->image。您没有发布呈现视图的控制器,所以我在这里猜测。


查看完整回答
反对 回复 2021-09-18
  • 2 回答
  • 0 关注
  • 166 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信