jeudi 29 mars 2018

conditional relationship for "with()"

I have a table called transactions and another table called cars with the below structure:

transactions

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

cars

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

A car has always a buy_transaction but not always a sell_transaction, situation is that I am trying to get all transactions (that might be car-related or not car-related) and include the CAR related to that transaction weather it is sold or bought, so I need to make the relationship conditional but i couldn't achieve that.

$journal = Transaction::with(
    ['user'=> function($query) { 
        $query->select('id', 'name');
     },
     'income',
     'outcome'
     'car'
    ])->where('date', '>=', $fromDate)->where('date', '<=', $toDate);

This is the modal class:

<?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');

        }
    }

}

I need to stick to that query structure because the query command is longer and I am joining and including other tables, I was hoping I could make the car() belongsTo relation conditional somehow.

I followed some similar situations like this but it didn't work for me.

Thank you.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2I9UCoz
via IFTTT

Aucun commentaire:

Enregistrer un commentaire