【问题标题】:What should I use to get an attribute out of my foreign table in Laravel?我应该使用什么来从 Laravel 的外部表中获取属性?
【发布时间】:2021-05-28 14:12:51
【问题描述】:

我正在尝试获取产品的价格。我正在使用一个 orderItem 表,它有一个指向产品表的外部 ID。然后我想访问相应产品的价格。当我这样做时,会出现此错误:此集合实例上不存在属性 [价格]。 当我死并转储 $orderItem->products_rel 时,我可以看到一个包含所有属性的数组。那么如何访问它们呢?

订单项表:

    <?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateOrderItemsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('order_items', function (Blueprint $table) {

            $table->id();
            $table->foreignId('product_id');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('order_items');
    }
}

产品表

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
            $table->foreignId('order_item_id');

            $table->string('name');
            $table->string('size');
            $table->float('price');
            $table->foreignId('topping_id')->nullable();



        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
}

产品型号

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\OrderItem;

class Product extends Model
{

    use HasFactory;
    protected $fillable = [
        'item_name', 'size', 'toppings','price',
    ];

    public function orderItem() {
        return $this->belongsTo(OrderItem::class,);

    }



}

订单商品型号

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\Product;

class OrderItem extends Model
{

    use HasFactory;

    protected $fillable =['product_id'];
    public function products_rel(){
      return $this-> hasMany(Product::class );

    }
    public function Order(){
    return $this->hasMany(Order::Class);
}
}

控制器

<?php

namespace App\Http\Controllers;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Product;
use Illuminate\Http\Request;

class OrderItemsController extends Controller
{

    public function index()
    {
//        $orderItems = OrderItem::with('products')->get();
        $orderItems = OrderItem::with('products_rel')->get();
//    $orderItems = OrderItem::all();
    return view('basket', ['orderItems'=> $orderItems]);
    }

    public function  create()
    {
        return view('welcome');
    }

    public function store ()
    {
    request()->validate([
        'item_name'=> 'required',
        'size'=> 'required',
        'desc'=> 'required',
        'price'=> 'required',

    ]);


        $orderPrice = Product::find('price')->orderItems() ->where('product_id')->first();
    OrderItem::create([

        'item_name' =>request('item_name'),
        'size' =>request('size'),
        'toppings' =>request('toppings'),
        'desc' =>request('desc'),
        'price' =>$orderPrice,
    ]);


    }
    public function pizzaCost(){

    }
}

BLADE.PHP

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
@foreach($orderItems as $orderItem)
 <p> {{$orderItem->products_rel->price}}</p>


@endforeach
</body>
</html>

【问题讨论】:

  • 每个产品都有很多相关的产品,所以products_rel是产品的集合,而不是单个产品。你必须遍历这些。
  • 我该怎么做?

标签: php database laravel eloquent


【解决方案1】:

products_rel,考虑到它是hasMany 关系,是产品的集合。您需要遍历这些以获取价格。

@foreach($orderItems as $orderItem)
  @foreach($orderItem->products_rel as $related_product)
    <p> {{$related_product->price}}</p>
  @endforeach
@endforeach

【讨论】:

  • 谢谢你现在说得通了:)
猜你喜欢
  • 1970-01-01
  • 2020-01-18
  • 2017-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-18
  • 2023-03-14
相关资源
最近更新 更多