【问题标题】:Adding product to wishlist laravel将产品添加到愿望清单 laravel
【发布时间】:2019-10-14 15:22:10
【问题描述】:

我正在创建一个允许用户在愿望清单中添加产品的功能,但是当我单击(愿望清单刀片)时出现错误Trying to get property of non-object,如果我删除,错误来自<h4>USD {{$wishlist->product->price }}</h4> 这一行$product 没有显示价格 我该如何解决?

愿望清单控制器

public function index()
{
     $user = Auth::user();
     $wishlists = Wishlist::where("user_id", "=", $user->id)->orderby('id', 'desc')->paginate(10);
     return view('wishlist', compact('user', 'wishlists'));
}

刀片

@if (Auth::user()->wishlist->count() )
@foreach($wishlists as $wishlist)

<h2>USD {{$wishlist->product->price }}</h2>
<h4>USD {{$wishlist->product->name }}</h4>

@endforeach
@endif

Wishlist.php

class Wishlist extends Model
{
protected $table = "wishlist";
protected $fillable=['product_id','user_id'];

public function user(){
   return $this->belongsTo(User::class);
}

public function product(){
   return $this->belongsTo(Product::class);
}
}

用户.php

 public function wishlist(){
    return $this->hasMany(Wishlist::class);
 }

产品.php

 public function wishlist(){
    return $this->hasMany(Wishlist::class);
 }

【问题讨论】:

  • 删除$...$wishlist-&gt;product-&gt;price

标签: php laravel laravel-5 eloquent


【解决方案1】:

首先,您应该像这样访问product 关系(删除$):

$wishlist->product->price

其次,您应该使用 ::with() 查询构建器立即加载愿望清单的 product

public function index()
{
     $user = Auth::user();

     $wishlists = Wishlist::with('product')
          ->where('user_id', $user->id)
          ->orderby('id', 'desc')
          ->paginate(10);

     return view('wishlist', compact('user', 'wishlists'));
}

另外,如果我是正确的,你的产品关系是错误的。

您的愿望清单应该有很多产品(而不是相反)。

在您的前端,您需要遍历愿望清单的所有产品:

@foreach($wishlist->products as $product)
    {{ $product->price }}
@endforeach

Wishlist 类中的关系更改为hasMany

public function products()
{
   return $this->hasMany(Product::class);
}

【讨论】:

  • 我仍然收到Trying to get property of non-object,但是当我 dd 时,我看到了产品@thisiskelvin
  • 所以你的关系不应该是你的愿望清单有很多产品,而不是你的愿望清单属于一个产品@user11710915
  • 如果我更改为whislist has many products,则会收到错误Unknown column 'products.wishlist_id' @thisiskelvin
  • @user11710915 您需要一个数据透视表来将愿望清单链接到愿望清单的产品。
  • 我应该将数据透视表放在模型中的什么位置? @thisiskelvin
【解决方案2】:

您应该首先更改检查愿望清单计数的方式,因为它会运行大量查询来恢复所有愿望清单然后计算它们。并按照@lucasArbex 的建议删除$product 中的$

@if ($wishlists->count() )
@foreach($wishlists as $wishlist)

<h2>USD {{$wishlist->product->price }}</h2>
<h4>USD {{$wishlist->product->name }}</h4>

@endforeach
@endif

同时更改您的控制器并使用您的用户的关系

public function index()
{
     $user = Auth::user();

     $wishlists = $user->wishlist()->with('product')
          ->orderby('id', 'desc')
          ->paginate(10);

     return view('wishlist', compact('user', 'wishlists'));
}

【讨论】:

  • 我已经尝试过你的答案仍然得到同样的错误@N69S
  • @user11710915 你能在你的问题中发布更多积压的错误吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-17
  • 1970-01-01
  • 2017-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多