流明口才关系

时间:2019-07-16 14:29:36

标签: eloquent lumen

更新

我的方法是接收与simpel mysql join相等的东西。我希望将来自tabel tx的所有具有project_id = x的条目与tx.id = txevent.tx_id上的txevent一起加入。

我正在使用流明5.5

更新2

以下原始sql可以完全满足我的要求:

$rawTx = DB::>table('tx')
            ->join('txevent', 'txevent.tx_id', '=', 'tx.id')
            ->where('tx.project_id', $request->get('project_id'))
            ->where('txevent.short_id', $request->get('short_id'))
            ->get();

通过关系是否有可能实现同样的目标?

END UPDATE

我有2张桌子txtxevent

发送:

id, int, autoincrement
project_id, int

txevent:

id, int, autoincrement
tx_id, int, fk(tx.id)
shortnumber, char

在tx.php中,我有以下方法:

public function txeventWithShortnumber($shortnumber)
{
    return $this->hasOne('App\Txevent')->where('shortnumber', $shortnumber)->first();
}
在TxController.php中,

我会做:

$tx = Tx::where('project_id', $request->get('project_id'))->txeventWithShortnumber($request->get('shortnumber'))->get();

结果是我收到以下错误消息:

(1/1)BadMethodCallException 调用未定义的方法Illuminate \ Database \ Query \ Builder :: txeventWithShortnumber()

在Builder.php第2483行中

有人可以告诉我我在做什么错吗?

1 个答案:

答案 0 :(得分:0)

我建议这样做:

Tx.php

public function txEvents()
{
  return $this->hasMany(TxEvent::class);
}

public function txeventWithShortnumber($shortNumber)
{
  return $this->txEvents->first(function($txevent) use ($shortNumber) {
     return $txevent->shortnumber == $shortNumber;
  });
}

在控制器中:

$tx = Tx::where('project_id', $request->get('project_id'))->get();

// attach shortNumber event
$tx->map(function($t) use ($request) {
    $t->eventWithShortNumber = $t->txeventWithShortnumber($request->get('shortnumber'));
});

$tx变量现在还将包含具有给定短号的txEvent。

我不确定是否可以动态地将条件传递给雄辩的关系。

相关问题