Limits to multiple Eloquent relationships ? - laravel-5

I have a number of different roles, who are all essentially "users" in my laravel app.
I'm having a problem with eloquent relationships where I can easily get one of the relationships, in the context of the user as a car owner, but when I try get another relationship in the context of a (different) user as a maintenance manager, I get this error: Cannot redeclare class App\Models\User.
serviceAgreement model
public function manager()
{
return $this->belongsTo('carfreak\Models\User','manager_id','id');
}
Works fine:
$managers = $owner->serviceAgreement()->get();
produces error
$managers = $owner->serviceAgreement()->with('manager')->get();
I'm thinking the problem lies somewhere in how I've written my relationship - my referring to the \Models\User. I've tried to refer to the logged in user, but it (a) doesn't make sense for this application and (b) doesn't work anyway.
return $this->belongsTo(Auth::User(),'manager_id','id');
Some pointers please?

That is happen because the App\Models\User class is declared at least 2 times. Change
public function manager()
{
return $this->belongsTo('carfreak\Models\User','manager_id','id');
}
to
public function manager()
{
return $this->belongsTo('App\Models\User','manager_id','id');
}
You should go fine now.
Hope it helps.

Related

Relations in laravel with model

The first i´m sorry for this question, i know that maybe it´s very bad. I´m reading much for relation with model in laravel but i don´t understand i don´t know to apply.
my problem it´s:
i have one Model session and i have one model patient one patient receive one or many session and one session it´s for one patient, ok¿?? My application it´s for physiotherapy clinic.
in my model Session i have this:
public function patient()
{
return $this->hasOne(Patient::class, 'id');
}
and in my model patient i don´t know if i have to to do anything or i have to to do this:
/**
* #return \Illuminate\Database\Eloquent\Relations\HasMnay
**/
public function sesiones()
{
return $this->hasMany(\App\Sesion::class, 'id');
}
one patient can get one or any sessions and one session it´s for one pattient i have more relations but i need to know to do one for to do next.
i´m doing this question, because my application web, returned this error:
STATUS_BREAKPOINT
and i think that my relations it´s bad and hang up my application
Thanks so much for help. And sorry for my question
updated
if i want to show doctor in sessions... I have this:
in model Session:
public function doctor(){
return $this->belongsTo(Doctor::class);
}
and in model Doctor
public function Doctor(){
return $this->belongsTo(Session::class);
}
but i can´t show in my table doctor that did this session
Based on your description, your eloquent relationship definition seems fine, although you don't need to specify the foreign key 'id' as it is referenced by default, the only modification I would make is maybe you could try to set the relationship as one patient has many sessions, and one session belongs to one patient
So in session model:
public function patient()
{
return $this->belongsTo(Patient::class);
}
and then in patient model:
public function sessions()
{
return $this->hasMany(Session::class);
}
Updated:
For doctor model:
public function sessions()
{
return $this->hasMany(Session::class);
}
and for Session Model:
public function doctor()
{
return $this->belongsTo(Doctor::class);
}
Although I don't think this is the reason to cause the error, just would make it easier to define foreign keys and relationships. Your status breakpoint error may cause by some other issues if you could describe more your workflow and how you get to that error

Laravel model to get specific piece of data

I am trying to make a function that will help me get needed data quickly.
With all the trials I have been able to get to the following
Tables:
Users (id,name)
Projects (id,name)
User-Project (id, user_id, project_id, manager) where manager is a boolean , there can only be one manager for each project (but employees can still see the project reason why we have a pivot table, manager = 0 for other normal users that can access that project)
In the Project Model I have:
public function Manager(){
return $this->belongsToMany('App\User')->wherePivot('manager', true);
}
In the View I have:
<p><strong>Project Manager:</strong> {{$project->manager}}</p>
On the actual page I get:
Project Manager: [{"id":4,"name":"Daniel Doe","email":"danieldoe#hotmail.com","phone":"70846556","email_verified_at":null,"created_at":"2020-12-20 21:05:50","updated_at":"2020-12-20 21:05:50","pivot":{"project_id":1,"user_id":4,"manager":1}}]
When I change the view to:
<p><strong>Project Manager:</strong> {{$project->manager[0]->name}}</p>
I get:
Project Manager: Daniel Doe
This is what I actually want but I would like to do it from the model if possible. So I tried:
public function Manager(){
return $this->belongsToMany('App\User')->wherePivot('manager', true)->first()->name;
}
But I get the following error:
must return a relationship instance
Can this be done from the model's function?
You can keep your defined relationship, but to access ->first()->name, you'll need to use an "Accessor":
public function manager() {
return $this->belongsToMany('App\User')->wherePivot('manager', true);
}
public function getManagerNameAttribute() {
return $this->manager->first() ? $this->manager->first()->name : 'No Manager';
}
Then, in your code, you simple access:
{{ $project->manager_name }}
If your manager() function returns a Collection of at least 1 record, it will return the name, otherwise it will display 'No Manager' as a fallback.
If you don't want to change the structure of this you can use an accessor to get this information, roughly something like this:
class Project ...
{
public function users()
{
return $this->belongsToMany(...)->withPivot(...);
}
public function getManagerAttribute()
{
return $this->users()->wherePivot('manager', 1)->first()?->name;
}
}
You can do this in different ways, you could use the loaded users relation and use a the Collection methods to filter the manager. You could create another relationship called managers that uses the wherePivot off of users(), etc ...
The only thing to worry about with this setup is that every call to $model->manager would be causing that query, so it may be a good idea to create another relationship manager so that you can load that once and keep using it without the need to keep querying the database:
public function managers()
{
return $this->users()->wherePivot(...);
}
public function getManagerAttribute()
{
return $this->managers->first()?->name;
}
Though, as mentioned already it is probably better to have something like a manager_id on the Project itself.

Laravel model create relationships twice between two tables

I am trying to create relation between two tables, users and messages in Laravel models, as the user can send a message to another user so that I have two foreign-keys (fromUser_id and toUser_id) as shown in the image below.
For the first relation it is straightforward that I will create a function with the name messages
public function messages(){
return $this->hasMany('App\Models\Message', 'fromUser_id');
}
However I do not know how to name the second relation as far as I know it should be messages too, according to the standard naming of Laravel, which will obviously issue an error as we have the first function with the same name.
public function messages(){
return $this->hasMany('App\Models\Message', 'toUser_id');
}
Would you please let me know what should I name it and how this will affect the models.
Well, you should not use simple messages as relationship but rather use receivedMessages and sentMessages like this:
public function sentMessages()
{
return $this->hasMany('App\Models\Message', 'fromUser_id');
}
public function receivedMessages()
{
return $this->hasMany('App\Models\Message', 'toUser_id');
}

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?

One to many relationship count - difference in accessing relationship

I have one to many relation - Entry can have many Visits.
In my Entry model I have the following methods:
public function visits() {
return $this->hasMany ('Visit', 'entry_id','id');
}
public function visitsCount() {
return $this->hasMany('Visit', 'entry_id','id')
->selectRaw('SUM(number) as count')
->groupBy('entry_id');
}
In Blade I can get number of visits for my entry using:
{{$entry->visits()->count() }}
or
{{ $entry->visitsCount()->first()->count }}
If I want to create accessor for getting number of visits I can define:
public function getNrVisitsAttribute()
{
$related = $this->visitsCount()->first();
return ($related) ? $related->count : 0;
}
and now I can use:
{{ $entry->nr_visits }}
Questions:
In some examples I saw defining such relation this way:
public function getNrVisitsAttribute()
{
if (!array_key_exists('visitsCount', $this->relations)) {
$this->load('visitsCount');
}
$related = $this->getRelation('visitsCount')->first();
return ($related) ? $related->count : 0;
}
Question is: what's the difference between this and the "simple method" I showed at the beginning? Is it quicker/use less resource or ... ?
Why this method doesn't work in this case? $related is null so accessor return 0 whereas using "simple method" it returns correct number of visits
I've tried also changing in visitsCount method relationship from hasMany to hasOne but it doesn't change anything.
1 Your relation won't work because you didn't select the foreign key:
public function visitsCount() {
// also use hasOne here
return $this->hasOne('Visit', 'entry_id','id')
->selectRaw('entry_id, SUM(number) as count')
->groupBy('entry_id');
}
2 Your accessor should have the same name as the relation in order to make sense (that's why I created those accessors in the first place):
public function getVisitsCountAttribute()
{
if ( ! array_key_exists('visitsCount', $this->relations)) $this->load('visitsCount');
$related = $this->getRelation('visitsCount');
return ($related) ? $related->count : 0;
}
This accessor is just a handy way to call the count this way:
$entry->visitsCount;
instead of
$entry->visitsCount->count;
// or in your case with hasMany
$entry->visitsCount->first()->count;
So it has nothing to do with performance.
Also mind that it is not defining the relation differently, it requires the relation to be defined like above.
Assuming your schema reflects one record / model per visit in your visits table, The best method would be to get rid of the visitsCount() relation and only use $entry->visits->count() to retrieve the number of visits to the entry.
The reason for this is that once this relation is loaded, it will simply count the models in the collection instead of re-querying for them (if using a separate relationship)
If your concern is overhead and unnecessary queries: My suggestion would be to eager-load these models in a base controller somewhere as children of the user object and cache it, so the only time you really need to re-query for any of it is when there have been changes.
BaseController:
public function __construct(){
if(!Cache::has('user-'.Auth::user()->id)){
$this->user = User::with('entries.visits')->find(Auth::user()->id);
Cache::put('user-'.Auth::user()->id, $this->user, 60);
} else {
$this->user = Cache::get('user-'.Auth::user()->id);
}
}
Then set up an observer on your Entry model to flush the user cache on save. Another possibility if you are using Memcached or Reddis would be to use cache tags so you don't have to flush the whole user's cache every time an Entry model is added or modified.
Of course, this also assumes that each Entry is related to a user, however, if it isn't and you need to use Entry alone as the parent, the same logic could apply, by moving the Cache class calls in your EntryController

Resources