【问题标题】:laravel 5 - Eloquent relationship two tableslaravel 5 - 雄辩的关系两张表
【发布时间】:2015-07-11 15:24:03
【问题描述】:

我是 Laravel 的新手,我有 2 类模型(表 Customer 和 Order):

table Customer, with columns:
  - id_cust (PK)
  - name

table Order, with columns:
  - id_order (PK)
  - id_cust (FK to table Customer)
  - product_name
  - qty

我尝试为“客户”制作模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Customer extends Model
{
    protected $primaryKey = 'id_cust';
    protected $table = 'customer';
}

和“订单”类的模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    protected $primaryKey = 'id_order';
    protected $table = 'order';
}

在 SQL 中:

select a.id_cust, a.name, b.product, b.qty
  from customer a, order b
 where a.id_cust = b.id_cust;

我想要这样的输出:

========================================
|id_cust  |name    |product    |qty    |
|======================================|
|10       |jeff    |Plastic    |10     |
|10       |jeff    |Book       |2      |
|11       |james   |Laptop     |1      |
|11       |james   |TV         |1      |
|12       |davy    |shoe       |1      |
========================================

我在控制器中尝试,但失败了:

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\customer;
use App\order;

class ShowDetail extends Controller
{

  public function index(){

    $aa = customer->where('customer.id_cust','=','order.id_cust')->order-get();
    var_dump($aa);
  }
}

有什么建议吗?

谢谢。

【问题讨论】:

    标签: laravel eloquent relationship


    【解决方案1】:

    在订单模型中:

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

    客户模型:

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

    然后在控制器中:

    public function index(){
        $aa= Customer::with('orders')->get();
        var_dump($aa);
    }
    

    【讨论】:

    • 嗨 Xhulio,谢谢你的回答,但它仍然失败,你能告诉我哪个部分解释了“... customer.id_cust = order.id_cust ...”之间的关系吗?谢谢。
    • 好的,在你的原始代码中试试这个:$aa = customer-&gt;where('customer.id_cust','order.id_cust')-&gt;get();
    • @Firdi 关系在您的模型中的 customer()order() 方法中。但是你也应该在你的数据库模型中定义它们
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-22
    • 2016-08-27
    • 1970-01-01
    • 2015-12-17
    • 2015-07-01
    • 1970-01-01
    相关资源
    最近更新 更多