php - 试图获取非对象的属性“产品”(Laravel 8)
问题描述
试图获取非对象的属性“产品”(查看:C:\xampp\htdocs\SSB280\resources\views\frontend\include\menubar.blade.php)
我认为我的产品 Eloquent 不起作用。
带有主要部分的模型 模型表。
class cart extends Model
{
use HasFactory;
public $fillable = [
'user_id',
'ip_address',
'order_id',
'product_id',
'product_quantity'
];
public function product(){
return $this->belongsTo(Product::class);
}
public static function totalPrice(){
if ( Auth::check() ) {
$carts = cart::Where('user_id', Auth::id() )->Where( 'order_id' , Null )->first();
}
else{
$carts = cart::Where('ip_address', request()->ip() )->Where( 'order_id' , Null )->first();
}
$total_price = 0;
foreach( $carts as $cart ){
if ( !is_null( $cart->product->offer_price ) ) {
$total_price += $cart->product_quantity * $cart->product->offer_price;
}
else{
$total_price += $cart->product_quantity * $cart->product->reguler_price;
}
}
return $total_price;
}
}
数据库
public function up()
{
Schema::create('carts', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->nullable();
$table->string('ip_address')->nullable();
$table->integer('order_id')->nullable();
$table->integer('product_id')->nullable();
$table->integer('product_quantity')->nullable();
$table->timestamps();
});
前端调用
这是我调用方法的地方
<div class="basket-item-count">
<span class="count">
{{ App\Models\Frontend\cart::totalItems() }}
</span>
</div>
<div class="total-price-basket">
<span class="lbl">cart -</span>
<span class="total-price">
<span class="sign">$</span>
<span class="value">{{ App\Models\Frontend\cart::totalPrice() }}BDT</span>
</span>
</div>
解决方案
您通过使用获得单个 Cart 对象
$carts = cart::Where('user_id', Auth::id() )->Where( 'order_id' , Null )->first();
接下来,您将对此进行分析。如果你想要多个 Cart 对象:
$carts = cart::Where('user_id', Auth::id() )->Where( 'order_id' , Null )->get();
为这两个查询更改它。
推荐阅读
- reactjs - 在 Visual Studio Code 中使用 useCallback() 获取 Typescript 错误
- git - 是否可以为每个 git 服务器指定不同的名称和电子邮件(使用子配置)?
- python - 从 bash 变量解析 Python 参数
- android - 电报android构建错误assembleAfatDebugTgVoipDex FAILED
- javascript - 试图让一个 REACT img 出现
- node.js - 使用 Html 文件作为 nodejs 中的模板,用于发送包含一些复杂级别数据的营销电子邮件
- gradle - 如何在build.gradle中以编程方式从具有动态版本的依赖项中获取已解析的版本(静态版本)?
- javascript - Vue 反应性不会拾取添加到数组中元素的新属性
- python - 部署 Heroku 应用程序时,我在 / 处得到 DisallowedHost - 但我已将 URL 添加到 ALLOWED_HOSTS
- javascript - 等待获取完成,直到返回数据