【问题标题】:Why is my @foreach statement not working in Laravel?为什么我的 @foreach 语句在 Laravel 中不起作用?
【发布时间】:2020-11-01 20:57:09
【问题描述】:

我正在创建一个 Laravel 电子商务网站,并且我正在使用 Voyager 作为后端。我在创建网站的“订单”部分时遇到了问题。我正在关注本教程:https://www.youtube.com/watch?v=0lo7vzO1Fto&list=PLEhEHUEU3x5oPTli631ZX9cxl6cU_sDaR&index=19

我正在为我的订单表覆盖 voyager 视图“read.blade.php”。我还将 BREAD 链接到一个名为 OrdersController.php 的控制器。

这个文件如下(我添加的附加代码如下):

<?php

namespace App\Http\Controllers\Voyager;

use App\Order;
use Validator;
use App\iamlush;
use Illuminate\Http\Request;
use TCG\Voyager\Facades\Voyager;
use TCG\Voyager\Events\BreadDataAdded;
use TCG\Voyager\Events\BreadDataUpdated;
use TCG\Voyager\Http\Controllers\VoyagerBaseController;

class OrdersController extends VoyagerBaseController
{
    //***************************************
    //                _____
    //               |  __ \
    //               | |__) |
    //               |  _  /
    //               | | \ \
    //               |_|  \_\
    //
    //  Read an item of our Data Type B(R)EAD
    //
    //****************************************

    public function show(Request $request, $id)
    {
        $slug = $this->getSlug($request);

        $dataType = Voyager::model('DataType')->where('slug', '=', $slug)->first();

        $isSoftDeleted = false;

        if (strlen($dataType->model_name) != 0) {
            $model = app($dataType->model_name);

            // Use withTrashed() if model uses SoftDeletes and if toggle is selected
            if ($model && in_array(SoftDeletes::class, class_uses_recursive($model))) {
                $model = $model->withTrashed();
            }
            if ($dataType->scope && $dataType->scope != '' && method_exists($model, 'scope'.ucfirst($dataType->scope))) {
                $model = $model->{$dataType->scope}();
            }
            $dataTypeContent = call_user_func([$model, 'findOrFail'], $id);
            if ($dataTypeContent->deleted_at) {
                $isSoftDeleted = true;
            }
        } else {
            // If Model doest exist, get data from table name
            $dataTypeContent = DB::table($dataType->name)->where('id', $id)->first();
        }

        // Replace relationships' keys for labels and create READ links if a slug is provided.
        $dataTypeContent = $this->resolveRelations($dataTypeContent, $dataType, true);

        // If a column has a relationship associated with it, we do not want to show that field
        $this->removeRelationshipField($dataType, 'read');

        // Check permission
        $this->authorize('read', $dataTypeContent);

        // Check if BREAD is Translatable
        $isModelTranslatable = is_bread_translatable($dataTypeContent);

        // Eagerload Relations
        $this->eagerLoadRelations($dataTypeContent, $dataType, 'read', $isModelTranslatable);

        $view = 'voyager::bread.read';

        if (view()->exists("voyager::$slug.read")) {
            $view = "voyager::$slug.read";
        }

        $order = Order::find($id);
        $products = $order->iamlush;

        return Voyager::view($view, compact('dataType', 'dataTypeContent', 'isModelTranslatable', 'isSoftDeleted', 'products'));
    }
}
$order = Order::find($id);      (this gets the order id)
$products = $order->iamlush;    (this gets the product info and is there retutned below)

return Voyager::view($view, compact('dataType', 'dataTypeContent', 'isModelTranslatable', 'isSoftDeleted', 'products'));

我的覆盖'read.blade.php'除了一个部分之外与正常相同:

<div class="panel-heading" style="border-bottom:0;">
    <h3 class="panel-title">Products In Order</h3>
</div>

<div class="panel-body" style="padding-top:0;">
    <ul>
        @foreach ($products as $product)
            <li style="margin-bottom: 10px">
                <div>Product Id: {{ $product->id }}</div>
                <div>Product Name: {{ $product->name }}</div>
                <div>Product Price: {{ $product->presentPrice() }}</div>
                <div>Product Quantity: {{ $product->pivot->quantity }}</div>
            </li>
        @endforeach
     </ul>
</div>

这应该返回我的数据库中保存的所有数据,但是,我得到了这个错误:

cmets 之后

这是我的 Order.php 模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    protected $fillable = [
        'user_id', 'billing_email', 'billing_name', 'billing_address', 'billing_city',
        'billing_province', 'billing_postalcode', 'billing_phone', 'billing_name_on_card',
        'billing_discount', 'billing_discount_code', 'billing_total', 'payment_gateway', 'error',
    ];

    public function user()
    {
        return $this->belongsTo('App\User');
    }

    public function products()
    {
        return $this->belongsToMany('App\iamlush')->withPivot('quantity');
    }
}

我相信'$products = $order->iamlush'这行在我的订单模型中引用了我的函数'products()',实际上应该是:

$products = $order->products

然后我运行它,我得到以下错误:

我认为问题可能是我创建 order_product 数据透视表的迁移表:

<?php

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

class CreateOrderProductTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('order_product', function (Blueprint $table) {
            $table->id();
            $table->integer('order_id')->unsigned()->nullable();
            $table->foreign('order_id')->references('id')
                ->on('orders')->onUpdate('cascade')->onDelete('set null');

            $table->bigInteger('product_id')->unsigned()->nullable();
            $table->foreign('product_id')->references('id')
                ->on('iamlushes')->onUpdate('cascade')->onDelete('set null');

            $table->integer('quantity')->unsigned();
            $table->timestamps();
        });
    }

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

【问题讨论】:

  • $products = $order-&gt;iamlush;这不是数组吗?
  • 它不应该是一个数组,我认为它指向我的模型
  • 那么它将是 $order-&gt;iamlush() ,可能是
  • 在您的控制器中,执行dd($products);,然后返回查看其中包含的内容。
  • @Qirel,我现在已经这样做了,发现它返回 null,所以该文件前面肯定有问题

标签: php laravel voyager


【解决方案1】:

错误提示找不到表。 您需要通过在终端或命令行中键入 php artisan migrate 来迁移表。

【讨论】:

    【解决方案2】:

    您可以在控制器顶部添加:

    Use DB;
    

    总是在我需要获取或更改数据时使用它。

    【讨论】:

    • 仅当您使用 DB 门面时,并非总是如此。如果您正在使用模型(大部分情况下应该使用模型),则不需要它。这不是关系返回 null 的原因。
    猜你喜欢
    • 1970-01-01
    • 2020-11-28
    • 2011-07-16
    • 2012-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多