试图建立一个在多个不同表中使用的Eloquent模型。以下是我的表格列表:
交易模型:
class Transaction extends Model
{
protected $table = 'transaction';
public function __construct($attributes = [], $date = null) {
parent::__construct($attributes);
$date = $date ?: "";
$this->setTable("transaction$date");
}
public function Receipt(){
return $this->belongsTo('App\Receipt');
}
}
收据模型:
class Receipt extends Model
{
protected $table = 'receipt';
public function transaction($date = null){
$transModel = new Transaction([], $date);
return $this->hasMany($transModel);
}
}
控制器:
$date = $request->date;
$newTableName = "transaction".$date;
$transModel = new Transaction([], $date);
$query = $transModel->selectRaw($newTableName.'.*, SUM('.$newTableName.'.amount) as amount')
->where($newTableName.'.user_id', $user->id)
->with('receipt.transaction')
->paginate($paginate);
当没有输入时,$ date = null,结果->数据如下(这是我想要的):
{
"id": 2005533,
"user_id": 12,
"receipt_id": "1002767",
"amount": "10.00000000",
"type": 2,
"created_at": "2018-12-18 11:57:22",
"receipt": {
"id": 1002767,
"remark": null,
"created_at": "2018-12-18 11:57:22",
"transaction": [
{
"id": 2005532,
"user_id": 12,
"receipt_id": "1002767",
"amount": "-10.00000000",
"type": 1,
"created_at": "2018-12-18 11:57:22",
},
{
"id": 2005533,
"user_id": 12,
"receipt_id": "1002767",
"amount": "10.00000000",
"type": 2,
"created_at": "2018-12-18 11:57:22",
}
]
}
},
当输入为201806时,$ date =“ 201806”,结果:
{
"id": 152,
"user_id": 12,
"receipt_id": "100",
"amount": "10.00000000",
"type": 2,
"created_at": "2018-06-10 11:57:22",
"receipt": {
"id": 100,
"remark": null,
"created_at": "2018-06-10 11:57:22",
"transaction": []
}
},
我现在面临的问题是$ date不为null时,我得到的结果是缺少收据交易。我可以知道该怎么做,以便在加载多个关系时知道应该指向哪个表吗?
$ date的预期结果!= null:
{
"id": 152,
"user_id": 12,
"receipt_id": "100",
"amount": "10.00000000",
"type": 2,
"created_at": "2018-06-10 11:57:22",
"receipt": {
"id": 100,
"remark": null,
"created_at": "2018-06-10 11:57:22",
"transaction": [
{
"id": 2005532,
"user_id": 12,
"receipt_id": "100",
"amount": "-10.00000000",
"type": 1,
"created_at": "2018-06-10 11:57:22",
},
{
"id": 152,
"user_id": 12,
"receipt_id": "100",
"amount": "10.00000000",
"type": 2,
"created_at": "2018-06-10 11:57:22",
}
]
}
},