Laravel Polymorphic get all models associated to a single model - laravel

I have an Attachment model which uses the morphs table and morphTo function. I have several models but the main ones include Client, Job, Project and Notes (which is also polymorphic) which can contain several Attachments.
A client is the top-level model. A Client has many Jobs. A Job has many Projects.
I am struggling with a single way to return all attachments of a client, including attachments of each Job, Project, and notes of each job/project under a client.
I currently am running several foreach loops and have a working way, but the queries on the page load range from 60-100 depending on the amount of jobs/projects/notes for each client. I run through each job to check if it has an attachment, if so, I loop through them. Then, I run through $job->notes->attachments and display those. From there, I dive into another foreach loop pulling all the job's projects, pulling the attachments from each project and then pulling all the notes and looping through that.
Is there a way within Laravel to get all of the Attachments that are somehow attached to a single Client without looping through the way I have? If not, is there a way I can optimize my loops so I don't have to request the attachments for each job/job's notes/project/project's notes?

I do this all the time. You just need a way to
"...get all of the Attachments that are somehow attached to a single
Client without looping through..."
You must consider custom joins, using Laravel Eloquent:
//client_id input here
$client_id = 10;
$att_from_client = Attachment::join('note', function ($join) {
$join->on('note.id', '=', 'attachment.object_id')
->where('attachment.object_type', 'App\\Note');
})
->join('project', 'project.id', '=', 'note.project_id')
->join('job', 'job.id', '=', 'project.job_id')
->join('client', 'client.id', '=', 'job.client_id')
->where('client.id', $client_id)
->get();
dd($att_from_client);

My advice is to use eloquent-has-many-deep. As example of you can do with that library you can look at the code of three models related with many to many:
class Role extends Model
{
public function users()
{
return $this->belongsToMany('App\Models\User')->withTimestamps();
}
public function permissions()
{
return $this->belongsToMany('App\Models\Permission')->withTimestamps();
}
}
class Permission extends Model
{
use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
public function roles()
{
return $this->belongsToMany('App\Models\Role')->withTimestamps();
}
public function users()
{
return $this->hasManyDeep('App\Models\User', ['permission_role', 'App\Models\Role', 'role_user']);
}
}
class User extends Authenticatable
{
use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
public function roles()
{
return $this->belongsToMany('App\Models\Role')->withTimestamps();
}
public function permissions()
{
return $this->hasManyDeep('App\Models\Permission', ['role_user', 'App\Models\Role', 'permission_role']);
}
}
With these relationships in place and 5 tables involved: users, role_user, roles, permission_role and permissions you can retrieve all the permissions of a User model with a call to $user->permissions, that resolves to only one query with all the joins needed.

Related

Laravel Create multiple records in Pivot table

I'm trying to create a function in our Laravel 5.8 app that would add multiple records to a pivot table. At present we have the following setup;
Users
Training Courses
Users Training Courses (pivot table for the above relationships, with a few extra fields)
I want to be able to show all users in the database, then check their name, pick a training course and hit "Add" and it'll create a record in the pivot table for each user that was selected.
I can't figure out where to start with this - it seems like I need to have a "for each user selected, run the store function" loop in the controller, but I have no idea where to start.
I wasn't sure if there was an easy way to do this in eloquent or not. Is there a simple way to do this?
Eloquent does this automatically if you set up the relationships correctly and you don't have to worry about pivot tables.
class Users
{
public function trainingCourses()
{
return $this->hasMany(TrainingCourses::class);
}
}
class TrainingCourses
{
public function user()
{
return $this->belongsTo(User::class);
}
}
Then you can use the save() method to create the relationship. But I find it better to wrap this function inside a helper method that you can use throughout your code:
class Users
{
...
public function assignTrainingCourse(TrainingCourse $trainingCourse)
{
return $this->trainingCourses()->save($trainingCourse);
}
}
In your code, you could then do something as simple as this:
$user = User::find(1);
$trainingCourse = TrainingCourse::find(1);
$user->assignTrainingCourse($trainingCourse);
Building on this, suppose you have the following route to assign a training course, where it expects a trainingcourse_id in the request:
Route::post('/users/{user}/trainingcourses', 'UserTrainingCoursesController#store');
Thanks to route model binding, Laravel can inference the parent model (user) from the URL, and your controller might look like this:
// UserTrainingCoursesController.php
public function store(User $user)
{
$trainingCourse = TrainingCourse::find(request()->input('trainingcourse_id'));
$user->assignTrainingCourse($trainingCourse);
return back();
}
Of course, you'll want to put some validation in here, but this should get you started.

Access Method in a hasManyThorugh

I have 4 tables,
props, listing, offers, contact
props has many listing, listing belongs to props
public function listings()
{
return $this->hasMany('App\Models\Listing\Listing');
}
offer belongs to listing,
public function property()
{
return $this->belongsTo('App\Models\Property\Property')->with('owners');
}
then
offer belongsToMany contact trough offer_contact table
public function buyers()
{
return $this->belongsToMany(Contact::class, 'offer_contact', 'offer_id', 'contact_id')->with('primary_email');
}
My question is, how to access buyers()?
Something like $props->buyers()
In props model, what I did is
return $this->hasManyThrough('App\Models\Offer\Offer', 'App\Models\Listing\Listing');
You cannot. You may use nested iterations to get properties, listings belongs to each property, offers belongs to each listing and then customers belonging with the offer.
Alternatively, you may use the raw query to get the desired result using DB::statement();
I created a HasManyThrough relationship with unlimited levels: Repository on GitHub
After the installation, you can use it like this:
class Property extends Model {
use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
public function buyers() {
return $this->hasManyDeep(Contact::class, [Listing::class, Offer::class, 'offer_contact']);
}
}

Can't get hasManyThrough to work

I've got three tables:
nCompanies (model Company)
nTransactions (model Transaction)
nBrokers (model Broker)
One company may have many transactions
One broker may have many transactions
Company and Broker doesn't have a relation.
Now I would like to get a list of brokers for each company through the company transactions. In order to do this I thought hasManyThrough() would do the job. But I can't get it to work.
Within my company model I have this:
class Company extends Model
{
protected $table = 'nCompanies';
protected $primaryKey = 'nCompanyId';
public function transactions()
{
return $this->hasMany('App\Transaction', 'nCompanyId');
}
public function brokers()
{
//This does not work
return $this->hasManyThrough('App\Broker', 'App\Transaction', 'nCompanyId', 'nBrokerId');
}
}
The below works, but I would prefer to do this with in the model in order to get a collection of brokers for each company, company->brokers instead of a flat list.
$companies = DB::table('nCompanies')
->join('nTransactions', 'nCompanies.nCompanyId', '=', 'nTransactions.nCompanyId')
->join('nBrokers', 'nTransactions.nBrokerId', '=', 'nBrokers.nBrokerId')
->selectRaw('nBrokers.*, nCompanies.*)
->groupBy('nCompanies.nCompanyId', 'nBrokers.nBrokerId')
->get();
How could I solve this? Should I use something else instead of hasManyThrough?
I re-read your question, and realized you wanted to get the brokers and companies through transaction. I guess you already have both nCompanyId and nBrokerId in transactions table. Then I guess the brokers should be accessed in Transaction model then so you can have:
class Transaction extends Model
{
public function brokers()
{
return $this->hasMany('App\Broker', 'nBrokerId');
}
}
So you can call it with:
$brokers = Company::find(1)->transactions->where('id', '1')->brokers();
This is just an example of my thoughts about this though:
I don't know if this helps you get what you are trying to do. :)
HasManyThrough does not work here because the relationship between Transaction and Broker is wrong: While there is a HasMany relationship Company->Transaction, there only is a HasOne relationship Transaction->Broker. For HasManyThrough to work, both have to be HasMany though.
A proposed solution would be to use an accessor together with a subquery in your model, like this:
public function getBrokersAttribute()
{
$transactionIds = $this->transactions->groupBy('nBrokerId')->lists('nBrokerId');
return Broker::find($transactionIds);
}
Be aware that this would cause two seperate queries, even though Laravel would cache the result of $transactionIds after first load. Also, this solution does not support eager loading and is not recommended when working with many companies.
Alternatively, you could use some looping to keep the ability of eager loading:
public function getBrokersAttribute()
{
$brokers = new Collection();
foreach ($this->transactions as $transaction) {
if (!$brokers->contains($transaction->broker->nBrokerId)) {
$brokers->add($transaction->broker);
}
}
return $brokers;
}
With this example, you can eager load using ->with('transactions.broker').

How do i access data using two BelongsTo?

I have three tables - "courses", "lessons" and "tasks". Each lesson belongsTo a course, and each task BelongsTo a lesson. I want to output a task, showing the task name, the lesson name, and the course name. How do I access the course table data? To get the lesson information linked to a course, I have used the following in my Task model:
$lessonName = $this->lessons->lesson_name;
To get the course name associated to that lesson, I have tried the following with no success, but I am really guessing here:
$courseName = $this->lessons->courses->course_name;
My model relationships are as follows:
Course.php
public function lessons()
{
return $this->hasMany('App\Lesson');
}
Lesson.php
public function tasks()
{
return $this->belongsTo('App\Task', 'task_id', 'id');
}
Task.php
public function lessons()
{
return $this->belongsTo('App\Lesson', 'lesson_id', 'id');
}
Where am I going wrong? Thanks
there is another way you can do this by using accessors.
on your Task model do the following:
public function getLessonAttribute(){
return Lesson::where('id', $this->attributes[*foreign_key_field*])->first();
}
Here you receive all the data regarding the lesson that the task belongs to, and can use them as any other attribute (field) of the model.
on your Lesson model get the course that it belongs to.
public function getCourseAttribute(){
return Course::where('id', $this->attributes[*course_foreign_key_field*])->first();
}
and then assuming that $task is your collection, you can access the lesson and the course like the following in blade:
$task->lesson->lesson_name and $task->lesson->course->course_name
In your lesson.php model doesn't exist relationship courses so there are your issue. Use answer what is told you #jeroenF
So you want the inverse of hasManyThrough?
The hasManyThrough feature of Laravel (see their site) facilitates connecting your Courses to Task directly, without having the intermediate connection in a separate relationship.
You are looking for the inverse?

Laravel 4: How to add more data to Auth::user() without extra queries?

I'm rather new to Laravel 4 and can't seem to find the right answer, maybe you can help:
A User in our application can have many Accounts and all data is related to an Account, not a User. The account the User is currently logged into is defined by a subdomain, i.e. accountname.mydomain.com.
We added a method account() to our User model:
/**
* Get the account the user is currently logged in to
*/
public function account()
{
$server = explode('.', Request::server('HTTP_HOST'));
$subdomain = $server[0];
return Account::where('subdomain', $subdomain)->first();
}
The problem is that there is always an extra query when we now use something like this in our view or controller:
Auth::user()->account()->accountname
When we want to get "Products" related to the account, we could use:
$products = Product::where('account_id', Auth::user()->account()->id)->get();
And yet again an extra query...
Somehow we need to extend the Auth::user() object, so that the account data is always in there... or perhaps we could create a new Auth::account() object, and get the data there..
What's the best solution for this?
Thanks in advance
Just set it to a session variable. This way, you can check that session variable before you make the database call to see if you already have it available.
Or instead of using ->get(), you can use ->remember($minutes) where $minutes is the amount of time you wish to keep the results of the query cached.
You should take a look at Eloquent relationships : http://laravel.com/docs/eloquent#relationships
It provides simple ways to get the account of a user and his products. You said that a user can have many accounts but you used a first() in your function I used a hasOne here.
Using Eloquent relationships you can write in your User model:
<?php
public function account()
{
// I assume here 'username' is the local key for your User model
return $this->hasOne('Account', 'subdomain', 'username');
}
public function products()
{
// You should really have a user_id in your User Model
// so that you will not have to use information from the
// user's account
return $this->hasMany('Product', 'account_id', 'user_id');
}
You should define the belongsTo in your Account model and Product model.
With Eager Loading you will not run a lot of SQL queries : http://laravel.com/docs/eloquent#eager-loading
You will be able to use something like
$users = User::with('account', 'products')->get();
To get all users with their account and products.
I think this is a good example for the purpose of Repositories.
You shouldn't query the (involved) models directly but wrap them up into a ProductRepository (or Repositories in general) that handles all the queries.
For instance:
<?php
class ProductRepository
{
protected $accountId;
public function __construct($accountId)
{
$this->accountId = $accountId;
}
public function all()
{
return Product::where('account_id', $this->accountId)->get();
}
}
//now bind it to the app container to make it globaly available
App::bind('ProductRepository', function() {
return new ProductRepository(Auth::user()->account()->id);
});
// and whenever you need it:
$productRepository = App::make('ProductRepository');
$userProducts = $productRepository->all();
You could group the relevant routes and apply a filter on them in order to bind it on each request so the account-id would be queried only once per repository instance and not on every single query.
Scopes could also be interesting in this scenario:
// app/models/Product.php
public function scopeCurrentAccount($query)
{
return $query->where('account_id', Auth::user()->account()->id);
}
Now you could simply call
$products = Product::currentAccount()->get();

Resources