【问题标题】:Retrieving relationships of relationships using Eloquent使用 Eloquent 检索关系的关系
【发布时间】:2019-08-24 20:09:47
【问题描述】:

我有一个包含以下表格和关系的数据库: 发票、订单和产品 每个因素都有几个订单,每个订单都指向一个产品。


发票型号:

class Invoice extends Model
{
    public function orders()
    {
        return $this->hasMany(Order::class);
    }
}

订购型号:

class order extends Model
{
    public function invoice()
    {
        return $this->belongsTo(Invoice::class);
    }
    public function product()
    {
        return $this->belongsTo('App\Product');
    }   
}

产品型号:

class product extends Model
{
    public function orders()
    {
        return $this->belongsToMany(Order::class);
    }
}

每个订单的名称是产品ID的外键,

$table->unsignedBigInteger('name')->references('id')->on('products')->default(0);

在我的模板中,我可以显示带有如下订单的发票:

{{$invoice->title}}
{{$invoice->client_address}}

@foreach($invoice->orders as $order)
    {{$order->name}}
    ${{$order->price}}
    {{$order->qty}}
    ${{$order->qty * $order->price}}
@endforeach

使用此功能:

public function show($id)
{
    $invoice = Invoice::with('orders')->findOrFail($id);
    return view('admin.invoice.show.main', compact('invoice'));
}

如何在订单记录中显示产品名称:

{{$order->product->name}}

我在单个循环中使用 before(例如,产品和类别) 但在这个例子中,我们有 3 个关系,并且之前使用了一个紧凑的方法。


我的产品表是:

Schema::create('products', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('name');
    $table->string('desc');
    $table->string('price');
    $table->string('image');
    $table->string('count');
    $table->string('status');
    $table->unsignedBigInteger('category_id')->default(0);
    $table->foreign('category_id')->references('id')->on('categories');

    $table->timestamps();
});

【问题讨论】:

  • 似乎是什么问题?

标签: laravel laravel-5 eloquent


【解决方案1】:

我认为你的关系是错误的......每个产品都可以在几个订单内......所以:

产品型号:


class product extends Model
{
    public function orders()
    {
        return $this->belongsToMany('App\Order');
    }
}

订购型号:

class order extends Model
{
    public function product()
    {
        return $this->hasOne('App\Product');
    }   
}

对吗?

然后访问:

$invoices = Invoice::with('orders.product')->get();

【讨论】:

  • 我有这个错误:SQLSTATE[42S22]: Column not found: 1054 Unknown column 'products.order_id' in 'where clause' (SQL: select * from products where products.@ 987654326@ in (150, 151))
  • 您的产品表的列是什么? @MohammadrezaAhmadpour
  • 不应该是ManyToMany关系吗?一个产品可以有多个订单,而一个订单可以包含多个项目?无论如何,如果您像这样更改关系,则需要更改表结构并将 order_id 外键字段添加到产品表中。
  • 我在主帖中添加了产品表的列。
  • @MohammadrezaAhmadpour 以及您保存 (order_product) 详细信息和连接的位置?
【解决方案2】:

试试这个

$invoice = Invoice::with('orders.product')->findOrFail($id);

你可以使用类似的东西访问

@foreach($invoice->orders as $order)
..
 {{ $order->product->name }}
..
@endforeach

【讨论】:

    猜你喜欢
    • 2013-09-28
    • 1970-01-01
    • 2019-08-24
    • 2021-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-17
    相关资源
    最近更新 更多