jeudi 20 août 2015

multicolumn "pivot" table query for Laravel model

after 2 days of looking on laravel docs and stackoverflow with no success I have to ask the question

I have 4 models so far and I am trying to get all related info in one go.

user model has relationship:

public function transactions() {
    return $this->hasMany( 'App\Transaction' );
}

store model has relationship: :

public function transactions() {
    return $this->hasMany( 'App\Transaction' );
}

product model has relationship: :

public function transactions() {
    return $this->hasMany( 'App\Transaction' );
}

and finally transaction model has relationships:

public function user() {
    return $this->belongsToMany( 'App\User' );
}
public function product() {
    return $this->belongsToMany( 'App\Product' );
}
public function store() {
    return $this->belongsToMany( 'App\Store' );
}

transaction table (looks like a pivot table):

transactions:
    id - integer
    user_id : integer
    product_id : integer
    store_id : integer
    ....... some additional columns containing transaction specific data.

I would like to get all transactions with referenced details for auth user

aka "$user->transactions" however with this i am getting only ids no data from related tables. I did try by joining but it looks messy and I think there is better way of getting this data well structured in laravel

the join looks like:

   $transactions = DB::table( 'transactions as t' )->where( 'user_id', Auth::id() )
    ->join( 'products', 'products.id', '=', 't.product_id' )
    ->join( 'stores', 'stores.id', '=', 't.store_id' )
    ->get( array( 't.id', 't.product_id', 'products.name as product_name', 't.store_id', 'stores.name as store_name' ) );

my objective is to get user object with all information about user including transactions and other details as one JSON response using as little queries as possible.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1JkcsOm
via IFTTT

Aucun commentaire:

Enregistrer un commentaire