Laravel 5.1 Querying Relationship - laravel

Learning Laravel by building a stock portfolio app. Have models for Users, Accounts, Stocks, Options, and Transactions. I believe I have the relationships set up properly.
Question is how do I get a Users->Account->Transactions. I'm sure I could just do something in query builder but I was hoping for a more "eloquent" approach.
User
public function accounts()
{
return $this->hasMany('App\Account');
}
public function stocks()
{
return $this->belongsToMany('App\Stock');
}
public function options()
{
return $this->belongsToMany('App\Option');
}
public function transactions()
{
return $this->hasMany('App\Transaction');
}
Account
class Account extends Model
{
protected $fillable =
[
'name',
'broker'
];
public function user()
{
return $this->belongsTo('App\User');
}
public function stocks()
{
return $this->belongsToMany('App\Stock');
}
public function options()
{
return $this->belongsToMany('App\Option');
}
public function transactions()
{
return $this->hasMany('App\Transaction');
}
Transaction
class Transaction extends Model
{
protected $fillable =
[
'type',
'account_id',
'transaction_date',
'quantity',
'stock_id',
'option_id',
'amount',
'description'
];
public function user()
{
return $this->belongsTo('App\User');
}
public function stock()
{
return $this->belongsTo('App\Stock');
}
public function option()
{
return $this->belongsTo('App\Option');
}
public function account()
{
return $this->belongsTo('App\Account');
}
public function accounts()
{
return $this->hasManyThrough('App\Account', 'App\User');
}
}
Ultimately, I guess I would be looking for a total amount for each account a user may have. (User can have many accounts and each account would have many transactions, stocks and options.)
Thanks for any help or at least letting me know if I am going down the right road!!

If $user is a User object then $user->accounts is a collection of Eloquent models
You can load all of the accounts and their transactions with eager loading:
$user->load([
'accounts',
'accounts.transactions',
]);
But $user->accounts->transactions isn't something you can do because "transactions" is a relation on each individual Account object, not on the collection of account objects. So to get the transactions you'd loop through each account:
foreach ($user->accounts as $account) {
// do something with $account->transactions;
}
I highly don't recommend doing this, as #alexw mentioned in his comment, Eloquent objects are pretty large and having x many x many is an exponentially large amount of data you're loading into memory. But generally, that's how you'd access relations of relations.
You're better off using the query builder
The good news is that relations can make querying really easy! For example, you could do something like this instead:
Note: in Laravel 5.2, the lists method has been replaced with pluck
$user->load(['accounts']);
foreach ($user->accounts as $account) {
$amounts = $account->transactions()->lists('amount');
$total = $amounts->sum();
// - or -
$query = $account->transactions()
->select(\DB::raw('SUM(amount) AS total'))
->first();
$total = $query->total;
}

Related

laravel relation data to search for other models

Client model has relations to Invoice. I need to get the amounts from the Invoice relationship and find the matching transactions from the Transaction model.
I do it like this:
class Client extends Model
{
public function invoices()
{
return $this->hasMany(Invoice::class);
}
public function priceInvoices()
{
return $this->hasMany(Invoice::class)->select('gross_price');
}
}
foreach (Client::find($id)->priceInvoices->toArray() as $item) {
$prices[] = $item['gross_price'];
}
$transactions_for_prices = Transaction::whereIn('price', $prices)->get();
Will it be possible to make it more elegant?
If your Invoice.php Model has a relationship with a Transaction.php Model,
Example:
class Invoice extends Model
{
public function trasnactions()
{
return $this->hasMany(Transaction::class);
}
}
You could do something like this in a controller. (example)
public function show($id) {
$client = Client::findOrFail($id);
return view('view_name', [
'client' => $client,
'transactions => $client->invoices->transactions
]);
}

Laravel relations pivot table name trouble

in my app I have 2 conversations types: normal private conversations between users and conversations for people which are interested of user product.
In my User model I declared relations like:
public function conversations()
{
return $this->belongsToMany('App\Conversation', 'conversation_user');
}
public function conversationsProduct()
{
return $this->belongsToMany('App\ConversationProduct', 'conversation_product_user', 'user_id', 'product_id');
}
Where 'conversation_user' and 'conversation_product_user' are pivot tables between 'users'-'conversations' and 'users'-'conversations_product' tables.
My conversation_user pivot table has conversation_id and user_id table properties, but conversation_product_user pivot table has additional property product_id.
In my Conversation Model I have:
public function users()
{
return $this->belongsToMany('App\User');
}
public function messages()
{
return $this->hasMany('App\Message');
}
In ConversationProduct Model I wrote:
protected $table = 'conversations_product';
public function users()
{
return $this->belongsToMany('App\User', 'conversation_product_user');
}
public function messages()
{
return $this->hasMany('App\MessageProduct');
}
In my ConversationProductController I have method to find user conversations:
public function showUserConversationsProduct(Request $request){
$user_id = $request->user_id;
//var_dump($user_id);
$userData = User::where('id', $user_id)->with('conversationsProduct')->first();
}
And there is my problem: In controller ->with('conversationsProduct') don't take relation for conversation_product_user, but for conversation_user pivot table. I can't handle it why its happen if I add second parameter as 'conversation_product_user' in my relation:
public function conversationsProduct()
{
return $this->belongsToMany('App\ConversationProduct', 'conversation_product_user', 'user_id', 'product_id');
}
I need protected $table = 'conversations_product'; to point my ConversationsProductController#store where to save conversation, but I think that can be problem with recognise proper relation.
I really appreciate any help. I attach photo of my db relations.

Defining relationship on pivot table elements in laravel

I'm building a small application on laravel 5.4 where I'm having following models and relationship:
Interaction Model:
public function contactsAssociation()
{
return $this->belongsToMany('App\Contact', 'contact_interaction', 'interaction_id', 'contact_id')->withPivot('company_id')->withTimestamps();
}
Contact Model:
public function company()
{
return $this
->belongsToMany('App\Company', 'company_contact','contact_id', 'company_id')->withTimestamps();
}
and Company Model:
public function contacts()
{
return $this->belongsToMany('App\Contact', 'company_contact', 'company_id','contact_id');
}
Now I'm fetching some data something like this:
$tempData['contacts'] = $interaction->contactsAssociation()->with('company')->get();
I want to extract company data from the pivot table which is mentioned in the relationship. Currently I can't find solution so I have to do:
$tempData['contacts'] = $interaction->contactsAssociation()->get();
$companies = [];
foreach($tempData['contacts'] as $contact)
{
$companies[] = Company::find($contact->pivot->company_id);
}
$tempData['company'] = $companies;
Guide me on this, thanks,
You can pass an array to the withPivot() function with every field you want to retrieve:
public function contactsAssociation()
{
return $this->belongsToMany('App\Contact', 'contact_interaction', 'interaction_id', 'contact_id')
->withPivot(['company_id', 'other_field'])
->withTimestamps();
}
Hope this helps you.

Laravel Eloquent - Get all records of child relation model

My data model is this:
Users > Offices > Organization
This is my model
class Organization extends Model {
protected $table = 'organizations';
public function offices()
{
return $this->hasMany('App\Models\Office');
}
public function users()
{
return $this->offices()->users();
}
....
So.. I want to get all users from an organization (of all the offices).
But I don't know how to do something like
$this->offices()->users();
(Avoiding user a manual collection or map to do that)
Thanks!
So, you have organization ID. You can load all users by using whereHas():
$users = User::whereHas('office', function ($q) use ($organizationId) {
$q->where('organization_id', $organizationId);
})
->get();
Make sure office() relationship is defined correctly in User model:
public function office()
{
return $this->belongsTo('App\Office');
}
Alternatively, you could define hasManyThrough() relationship:
public function users()
{
return $this->hasManyThrough('App\Office', 'App\User');
}
And use it:
$organization->users()

Laravel Eloquent hasMany and BelongsToMany not returning using with

I am trying to do a single query to get back an order and the card to charge, but getting an error.
Card model:
class Card extends Eloquent {
protected $guarded = array();
public static $rules = array();
public function user()
{
return $this->belongsTo('User');
}
public function orders()
{
return $this->hasMany('Order');
}
}
Order model:
class Order extends Eloquent {
protected $guarded = array();
public static $rules = array();
public function user()
{
return $this->belongsTo('User');
}
public function card()
{
return $this->hasOne('Card');
}
public function address()
{
return $this->belongsTo('Address');
}
public function orderItems()
{
return $this->hasMany('OrderItem');
}
}
What I am trying to get back:
$order = Order::with('card')->find($id);
This obviously doesn't work and I have tried several combos. I think the issue is with my models/relationships.
Any idea how I can get back the order with the card/token details?
DB info: Each order can have only one card_id and each card can be in many orders. There is no order_id in the card.
Orders table basically:
id | card_id
Cards table:
id | token
Trying to get the token col to return with the Order.
In your Order model, you need to change this:
public function card()
{
return $this->hasOne('Card');
}
to this:
public function card()
{
return $this->belongsTo('Card');
}
The reason is that you are defining the inverse of the hasMany relationship. With the belongsTo relationship, Eloquent will look for a card_id column on the orders table.

Resources