【发布时间】:2020-11-22 13:01:33
【问题描述】:
我正在制作一个项目,我在产品中使用商店的外键。外键有效,但是当我想使用 $product->shop_id->shop_name 在刀片中显示它时,它给出了一个空白点。我的外键名为“shop_id”。Product page without shop name
这是我的代码:
产品控制器:
public function getProduct()
{
$products = DB::table('products')->inRandomOrder()->simplePaginate(15);
return view('product', ['products' => $products]);
}
product.blade.php
@foreach($products as $product)
<div class="column4 ">
<div class="box ProductPage">
<img src="{{$product->product_image}}" alt="" class="image image-full"/>
<h3>{{$product->product_name}}</h3>
<p>Inhoud: {{$product->product_volume}}</p>
<p><u>€{{$product->product_price}}</u></p>
<p>Winkel:{{$product->shop_id->shop_name}}</p>
</div>
<a href="{{$product->product_url}}" class="button button-small">Bekijk product</a>
</div>
产品型号
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasFactory;
/**
* @var string
*
*
*/
protected $table = 'products';
/**
* @var array
*
*
*/
protected $fillable = [
'product_name', 'product_volume', 'product_price', 'product_url', 'product_image',
];
/**
* @return \Illuminate\Database\Eloquent\Relations\HasOne
*
*
*/
public function shop()
{
return $this->hasOne('App\Shop', 'shop_id');
}
}
店铺模型
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Shop extends Model
{
use HasFactory;
/**
* @var string
*
*
*/
protected $table = 'shops';
/**
* @var array
*
*
*/
protected $fillable = [
'shop_name',
];
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function product()
{
return $this->belongsTo('App\Product', 'shop_id')->withDefault();
}
}
【问题讨论】:
-
从
$product->shop_id更改为$product->shop -
shops和products表上的主键列名称是什么?它是默认的id还是您已将其更改为其他内容? @daan-verweij