UPDATE
My approach is to receive something equal to a simpel mysql join. I want all entries from tabel tx with project_id = x joined with txevent on tx.id = txevent.tx_id.
I´m using lumen 5.5
UPDATE 2
The following raw sql will do exactly what I want:
$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();
Isn´t it possible to achieve the same with relations?
END UPDATE
I´ve got 2 tables tx
and txevent
:
tx:
id, int, autoincrement
project_id, int
txevent:
id, int, autoincrement
tx_id, int, fk(tx.id)
shortnumber, char
in tx.php I´ve got the following method:
public function txeventWithShortnumber($shortnumber)
{
return $this->hasOne('App\Txevent')->where('shortnumber', $shortnumber)->first();
}
in TxController.php I´ll do:
$tx = Tx::where('project_id', $request->get('project_id'))->txeventWithShortnumber($request->get('shortnumber'))->get();
as result I get the following error message:
(1/1) BadMethodCallException Call to undefined method Illuminate\Database\Query\Builder::txeventWithShortnumber()
in Builder.php line 2483
Can someone tell me what I´m doing wrong?
I recommend to do it this way:
In 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;
});
}
In controller:
$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
variable will now hold txEvents with the given short number as well.
I am not sure if you can dynamically pass condition to an eloquent relationship.