【问题标题】:conditional relationship for "with()"“with()”的条件关系
【发布时间】:2018-09-08 03:52:36
【问题描述】:

我有一个名为transactions 的表和另一个名为cars 的表,其结构如下:

transactions

| id  | date | amount | status | user_added |
| --- | ---- | ------ | ------ | ---------- |

cars

| id  | plate | specs | buy_transaction  | sell_transaction  |
| --- | ----- | ----- | ---------------- | ----------------- |

汽车总是有buy_transaction,但并不总是sell_transaction,情况是我正在尝试获取所有交易(可能与汽车相关或不与汽车相关)并包括与该交易相关的CAR天气它被出售或购买,所以我需要使这种关系有条件,但我无法实现。

$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,但它对我不起作用。

谢谢。

【问题讨论】:

  • 我猜你应该将 Transaction:car() 方法拆分为两种不同的方法:Transaction:soldCar() 和 Transaction:boughtCar()。
  • 谢谢,我已经试过了,但我不能,因为以后我会使用返回的结果作为一个json数组,它必须在car节点下,不管是卖还是买。

标签: laravel laravel-5


【解决方案1】:

您发布的链接有答案

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

【讨论】:

  • 我已经尝试过了,我收到了一个错误Undefined variable: query,当我使用scopeCar($query) 时,我收到另一个BadMethodCallException 错误Call to undefined method Illuminate\Database\Query\Builder::addEagerConstraints()
  • 我编辑了我的答案,忘记在评分功能上收到$query
  • 我刚刚在上面提到我已将您的答案更正为scopeCar($query),但我得到了另一个错误,type 也必须是status
  • 如果状态为整数,则从when条件中删除'
  • 不是字符串,谢谢 :( Call to undefined method Illuminate\Database\Query\Builder::addEagerConstraints()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-21
  • 2021-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多