嗨,我正在尝试根据订单交易的ID创建记录库。
我这里有ORDERS,CAMPANIES和CURRENCIES模型。
现在,我希望ORDER从URL参数获取ID,然后公司应该从与货币相同的订单中抢夺company_id
,我想从订单中抢夺currency_id
。
这是我到目前为止的想法:
public function create($order_id)
{
$order = Orders::find($order_id)->where('id', '=', $order_id)->get();
$company = Companies::where('id', '=', $order['company_id'])->get();
$currency = Currencies::where('id', '=', $order['company_id'])->get();
$banks = Banks::all('name','acronym','id')->get();
return view('orderPayments.create', compact('order'))
->with('company', $company)
->with('currency', $currency)
->with('banks', $banks);
}
货币模型
public function orderPayments()
{
return $this->hasMany('App\Orderpayments', 'id','currency_id');
}
公司模式
public function orderPayments()
{
return $this->hasMany('App\Orderpayments', 'id','company_id');
}
订单付款模式
public function company()
{
return $this->hasOne('App\Companies', 'id','company_id');
}
public function currency()
{
return $this->hasOne('App\Currencies', 'id', 'currency_id');
}
public function bank()
{
return $this->hasOne('App\Bank', 'id', 'currency_id');
}
如何实现?提前非常感谢您!
我刚刚应用了@sandy的答案。我检查了$ order是否有内容,所以我通过执行以下操作回显了$ order,{{$ order}}返回值可以。
但是当我调用$ order-> grandtotal或$ order-> companies-> comp_name等其他属性时,错误是
答案 0 :(得分:1)
如果模型之间的关系是One To Many关系,则应在关系中使用belongsTo
,如下所示:
订单付款模式
public function company()
{
return $this->belongsTo('App\Companies','company_id');
}
public function currency()
{
return $this->belongsTo('App\Currencies','currency_id');
}
public function bank()
{
return $this->belongsTo('App\Bank', 'currency_id');
}
此外,函数上的第二个参数应该是您的外键。
回答您的问题:
如果要访问给定订单的关系,可以执行以下操作:
$order = Order::find($order_id);
$order->company; // this will return the company
$order->currency; // this will return the currency
如果要在视图中显示:
{{$order->company->anyCompanyAttribute}}
注意: 您应该以 SINGULAR (货币,公司)之类的名称命名您的模型。不是复数。
答案 1 :(得分:0)
尝试这样
$order = Orders::with(['company','currency'])->where('id', '=', $order_id)->get();