Eloquent 与自身条件的关系

Eloquent relation with condition where it self

我在调用条件自身的关系时遇到问题

这是我的方案

table bank
|id|cash_id|type

table cash_small
|id|title|

table cash_big
|id|title|

我需要根据 table 银行

type 的关系调用动态条件
public function small(){
  return $this->belongsTo('App\CashSmall', 'cash_id')->where('type','small');
}

public function big(){
  return $this->belongsTo('App\CashSmall', 'cash_id')->where('type','big');
}

但结果是,条件在关系 table 上起作用,不在银行 table

你能帮我解决这个问题吗?

谢谢

不确定为什么 small_cashbig_cash 有 2 个不同的 table。有一个名为 cash 的 table 和一个名为 type 的字段。然后你可以使用 laravel 局部作用域。

因此在您的模型中 Bank.php 您将拥有一种称为现金的关系。

public function cash() 
{
  return $this->belongsTo('App\Cash', 'cash_id');
}

现在 Cash.php 您可以像这样创建范围

public function scopeSize($query, $type = 'small') //can be whatever you want
{
    return $query->where('type', $type);
}

现在您所要做的就是在需要时添加查询范围,就像这样$bank->cash()->size('small');

现在您的 cash() 方法将 return 所有现金并添加范围以过滤您想要的结果。

更多信息请查看 laravel 范围文档。 https://laravel.com/docs/5.5/eloquent