【问题标题】:Using foreign key to get all product from another table?使用外键从另一个表中获取所有产品?
【发布时间】:2018-05-15 09:25:25
【问题描述】:

我有两个表 Order_table 和 Invoice_table,我有 Order_table 的 order_id,它是 Invoice_table 的外键。 在 Laravel 中如何编写这种情况下的查询。

【问题讨论】:

  • 嗨,Probir,我们需要表定义。
  • 用你的键盘!请提供 MVCE,以便我们提供帮助。 stackoverflow.com/help/mcve
  • 感谢您的评论,我已经解决了。

标签: mysql laravel


【解决方案1】:

你应该尝试使用雄辩的关系来解决这类问题。您可以在这里查看参考https://laravel.com/docs/5.6/eloquent-relationships#one-to-one

正如你所说,你应该只在 invoices 数据库表中包含 _"order_id"_ 列。

在您的 Order.php 模型中,编写以下代码:

public function invoice()
        {
            return $this->hasOne('App\Invoice');
        }

在您的 Invoice.php 模型中,编写以下代码:

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

从 Controller 你可以使用 eloquent 查询来获取数据。例如,您可以使用此代码获取随机 3 个数据:

$results = Invoice::limit(3)->get();
      echo $results->order;

【讨论】:

  • 感谢您的帮助.. :)
【解决方案2】:

如果我们假设模型的名称是Invoice 和Order,你可以使用这个代码:

$invoice = Invoice::find($invoice_id);
$orders = $invoice->orders();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-08
    • 2019-11-07
    • 1970-01-01
    • 2021-12-16
    相关资源
    最近更新 更多