产品数据已存储在数据库中,但数据无法显示在心愿单页面中。我该如何解决??
public function wishList(Request $request)
{
$products = wishlist::where('wishlist.pro_id','=','products.id')->get();
return view('wishlist',compact('products'));
}
public function addWishList(Request $request){
$wishList = new wishList;
$wishList->user_id = Auth::user()->id;
$wishList->pro_id = $request->pro_id;
$wishList->save();
}
这是我想展示产品的心愿单页面。。是数据无法从数据库中获取吗?
<tbody>
@forelse($products as $product)
<tr>
<td>
<img src="{{url('/assets/images/products')}}/{{AppProduct::findOrFail($product->product)->feature_image}}" alt="">
</td>
<td>
/*product name*/
<a href="{{url('/product',$product->id)}}">
{{$product->title}}
</a>
</td>
</tr>
@empty
<tr>
<td colspan="6">
<h3>Your WishList Is Empty</h3>
</td>
</tr>
@endforelse
<tr>
<td colspan="4">
<a href="{{url('/')}}" class="shopping-btn">{{$language->continue_shopping}}</a>
</td>
</tr>
</tbody>
我认为问题出在愿望列表查询中:
$products = wishlist::where('wishlist.pro_id','=','products.id')->get();
这将产生sql查询
SELECT * FROM wishlist WHERE wishlist.pro_id = 'products.id'
它不会抛出mysql异常,因为"products.id"是字符串,我认为这不是您想要的查询。
我想你必须加入products
表格上的愿望清单,然后使用whereRaw
或where(DB::raw('...')
查询生成器语法
whereRaw:
Wishlist::whereRaw('wishlist.pro_id = products.id')->get()
其中:
Wishlist::where(DB::raw('wishlist.pro_id = products.id'))->get()
尝试使用@foreach而不是@forelse
@foreach($products as $product)
<tr>
<td>
<img src="{{url('/assets/images/products')}}/{{AppProduct::findOrFail($product->product)->feature_image}}" alt="">
</td>
<td>
/*product name*/
<a href="{{url('/product',$product->id)}}">
{{$product->title}}
</a>
</td>
</tr>
@endforeach
@else
<tr>
<td colspan="6">
<h3>Your WishList Is Empty</h3>
</td>
</tr>
@endif
首先,在执行查询的同一行中调用属性是一种糟糕的做法。此外,在控制器中,您将Wishlist表中的product id称为prod_id,而在模板中将其称为product。
<tbody>
@forelse($products as $product)
<tr>
<td>
@php
$prod = AppProduct::findOrFail($product->prod_id)) // prod_id not product
@endphp
@if($prod)
<img src="{{url('/assets/images/products')}}/{{ $prod->feature_image }}" alt="">
@endif
</td>
<td>
/*product name*/
<a href="{{url('/product',$product->id)}}">
{{$product->title}}
</a>
</td>
</tr>
@empty
<tr>
<td colspan="6">
<h3>Your WishList Is Empty</h3>
</td>
</tr>
@endforelse
<tr>
<td colspan="4">
<a href="{{url('/')}}" class="shopping-btn">{{$language->continue_shopping}}</a>
</td>
</tr>
</tbody>
我不确定您是否打算使用$product->title作为愿望列表对象或您在模板上创建的产品查询的一部分。如果您指的是产品查询,那么您将在If条件中包含其余代码,并使用$prod->title