首先在模型中定义方法。
Customer.php // Customer model
class Customer extends Model
{
protected $table = 'customers';
protected $primaryKey = 'customer_id';
public function customerItems(){
//customer_id is a foreign key in customer_items table
return $this->hasMany(Item::class, 'customer_id');
// A customer will has many items thats why hasMany relation is used here
}
}
CustomerItem.php // CustomerItem
class CustomerItem extends Model
{
protected $table = 'customer_items';
protected $primaryKey = 'customer_item_id';
public function itemDetail(){
//customer_id is a foreign key in customer_items table
return $this->hasOne(Customer::class, 'customer_item_id');
//A Item will has single detail thats why hasOne relation used here
}
}
在 CustomerController.php
use \Customer // define customer model path
public function getCustomerItem(Request $request)
{
// Eloquent query to get data
$customer_item_detail_data = Customer::with('customerItems.itemDetail')->get();
//it return all items of customers with item details
//$customer_item_detail_data = Customer::with('customerItems')->with('customerItems.itemDetail')->get(); you can also use in this way
}
希望能帮助到你。谢谢你。