我有一个名为transactions的表和另一个名为cars的表,其结构如下:
transactions
| id | date | amount | status | user_added |
| --- | ---- | ------ | ------ | ---------- |cars
| id | plate | specs | buy_transaction | sell_transaction |
| --- | ----- | ----- | ---------------- | ----------------- |一辆汽车总是有一个buy_transaction,但不总是一个sell_transaction,情况是,我试图得到所有的交易(可能是与汽车相关的或不与汽车相关的),并包括与该交易相关的汽车,它被出售或购买,所以我需要使关系有条件,但我不能做到这一点。
$journal = Transaction::with(
['user'=> function($query) {
$query->select('id', 'name');
},
'income',
'outcome',
'car'
])->where('date', '>=', $fromDate)->where('date', '<=', $toDate);这是模态类:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Transaction extends Model
{
public function income()
{
//.....
}
public function outcome()
{
//.....
}
public function user()
{
return $this->belongsTo('App\User', 'user_added', 'id');
}
// *** problem starts here ***
public function car()
{
if (transaction status == 1) {
return $this->belongsTo('App\Car', 'id', 'sell_transaction');
}
else if (transaction status == 2) {
return $this->belongsTo('App\Car', 'id', 'buy_transaction');
}
}
}我需要坚持这个查询结构,因为查询命令更长,而且我要加入并包含其他表,我希望我能以某种方式使car() belongsTo关系具有条件。
我跟踪了一些类似的情况,like this,但它对我不起作用。
谢谢。
发布于 2018-03-29 09:18:19
你发布的链接有答案
public function soldCar()
{
return $this->belongsTo('App\Car', 'id', 'sell_transaction');
}
public function boughtCar()
{
return $this->belongsTo('App\Car', 'id', 'buy_transaction');
}
public function scopeCar($query)
{
return $query->when($this->type === '1',function($q){
return $q->with('soldCar');
})
->when($this->type === '2',function($q){
return $q->with('boughtCar');
});
}编辑:,这看起来是多义性关系的一个主要例子,如本文所记录的https://laravel.com/docs/5.5/eloquent-relationships#polymorphic-relations
https://stackoverflow.com/questions/49551833
复制相似问题