laravel一对多关系返回null

问题描述 投票:0回答:3

有两种型号。产品和图片在我的产品型号中:

// one to many   relationship with images table 
public function images()
{
    return $this->hasMany('App\image');
}

图像模型

public function product()
{
    return $this->belongsTo('App\product');


}

ProductController的

public function productDetail($slug)
{
    $product = product::where([
      ['slug',$slug],
      ['seller_id' ,Auth::id()],
    ])->first();
    //$storagePath = Storage::get(['images']);
    //get the image of that product 
    //$image   = asset('storage/product_images'.$product->images);



    if($product)
    {
      $image    = Storage::url($product->images); // give the image path from product table

      //give images from the image table 
      $product_image   = \App\product::find(11)->images;
         $arr = array();

          foreach(\App\product::find($product->id)->images() as $i)
          {
            array($arr,$i->image);
          }

          dd($arr);  // problem returning always null 






      return view('backEnd.seller.product_detail',compact('product','image')); 
    }

问题陈述:在我的控制器中,当我试图获取特定产品的所有图像时,我得到Null。我试图在一天前解决这个问题。请帮助我,我错过了什么?

图像表迁移

public function up()
{
    Schema::create('images', function (Blueprint $table){
        $table->increments('id');
        $table->unsignedInteger('product_id');
        $table->string('image');
        $table->timestamps();
    });
}

产品表迁移

public function up()
{
    Schema::create('products', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('seller_id');
        $table->unsignedInteger('category_id');
        $table->string('product');
        $table->text('discription');
        $table->string('type')->nullable();
        $table->date('date');
        $table->string('images');
        $table->string('slug');
        $table->integer('sold_qty')->default(0);
        $table->timestamps();
    });
}

注意:我已经确保在我的图像表中有5条product_id记录。请帮助谢谢

database null foreign-keys relationship laravel-5.6
3个回答
0
投票

您必须在数据库中建立关系。您可以通过将其添加到图像迁移来实现:

$table->foreign('product_id')->references('id')->on('product');

0
投票

我假设你的模型名称是ProductImage

请检查以下更改是否会为您提供您想要的...

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

请注意,型号名称以大写字母开头,

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

和@ steve-trap所提到的数据库约束不是必需的。无论如何,它会引入一个约束,以便您不能为不存在的产品添加图像。

然后在控制器中:

foreach (App\Product::find($product->id)->images as $image) {
    $arr[] = $image->image;
}

0
投票

我解决了这个问题:

  1. 将模型名称更改为大写。
  2. 更改了产品表列名称图像以覆盖。
  3. 将方法images()更改为Product Model中的图片

结论:如果使用列名,则不要将该列名用于构建关系。并始终写出以大写字母开头的模型名称。

© www.soinside.com 2019 - 2024. All rights reserved.