laravel 5 - 雄辩关系两张桌子

时间:2015-07-11 15:24:04

标签: laravel eloquent relationship

我是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';
}

和'Order'类的模型:

<?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);
  }
}

任何建议?

谢谢。

1 个答案:

答案 0 :(得分:0)

在订单模型中:

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);
}
相关问题