Relations in laravel with model - laravel

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

Related

Laravel - why is a Model's relations not being loaded?

I have a Laravel 5.3 site and I think maybe I have some weird things going on due to some actions happening in API controllers and some happening in the regular controllers.
Or maybe an issue where at some times I am dealing with a Model, and sometimes with an Eloquent Collection.
The issue is, I am trying to retrieve relations on a Model and am getting null.
For instance, I have course Model that relates to week Model.
In course Model I get week items as
public function weeks()
{
return $this->hasMany(Week::class, 'course_id');
}
In backend, these relations get sent in this way:
$course->load('weeks')
All is good.
But when course item gets deleted and I try and take action in the week controller as
static::deleting(function($course) {
$course->weeks->delete();
});
$course->weeks is null. At that time I see in the database that all is good and this course items does indeed have a week item related, but $course shows 0 relations.
So something odd is happening where $course->webinars is not grabbing the week items related.
Is there something that I am fundamentally doing wrong? Maybe it is because in the models I have these sorts of statements:
protected $table = 'Week';
Are these preventing the relations from being pulled? I always thought that is I had some function in a model that returns relations that those relations would always be available when I use syntax $course->weeks.
Ideas?
Thanks again,
You can simply setup migrations to automatically delete from weeks if you delete a course, provided you have foreign key relationship.
If you have a column course_id in weeks table then add this into your migration
$table->foreign('course_id')
->references('id')->on('courses')
->onDelete('cascade')
I think you can use Observers. In your AppServiceProvider, first register the observer.
public function boot()
{
Course::observe(CourseObserver::class);
}
Now, add an Observer class.
class CourseObserver
{
public function deleting(Course $course)
{
$course->weeks()->delete();
}
}

A model with polymolymorphic ony to many and simple one to many relationship

I am using laravel 5.7. I have now a situation where i have a Fight model with structure user_id, fightable_id
i have two other tables users and monsters. so users_id refers to users (a user can have many fights) and fightable_id can refer to either a user or a monster (monsters table). so I have to define the functions for the relation ship
for User model i have to do
1.for polymorphic one to many relationship
public function fights()
{
return $this->morphMany('App\Fight', 'fightable');
}
2.for simple one to many relationship
public function fights()
{
return $this->hasMany('App\Fight');
}
I am confused now. ofcourse the only way is to change the functions name. but i will be doing the correct thing by changing the function names right (as both the functions have same name). or is there anything I am doing wrong?
I'm not sure I understand your question completely but I'll try my best!
Also this post will really help you understand the problem you are facing I think,
Laravel morph relationship
Using the code from the post I linked but taking your tables would produce models defined like this.
User Model
class User extends Model
{
public function fights()
{
return $this->hasMany('App\Fight');
}
}
Fight Model
class Fight extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
public function fightable()
{
return $this->morphTo();
}
}
Monster Model
class Monster extends Model
{
public function fight()
{
return $this->morphOne('App\Fight', 'fightable');
}
}
If you still feel this has not answered your question or need some more help just let me know!

How to eloquent relationship with multiple results

Problem
I have two classes, Users & Posts. A user "hasMany" posts and a post "belongTo" a user. But when I call "User::all()" it doesn't automatically pull the users posts for obvious reasons, because if my user had relations to 100 different tables pulling all users would start to become pretty chunky.
Question
Is there a way to pull all users and all user->posts in one or few lines of code without going through a foreach loop?
I know i can use a mutator but the problem I have is my field is called user_id and i have tested it with this code:
public function getUserIdAttribute($id)
{
return User::find($id);
}
But it will replace "user_id" field value with a user object, Id rather have it set to its own "temporary user" field within the result. I'm trying to find best practice!
Thank you in advance.
What you're looking for is called Eager Loading
Inside your post model :
class Post extends Model
{
protected $table='posts';
public $primaryKey='id';
public function user(){
return $this->belongsTo('App\User','user_id');
}
}
now you want to get post with user use below code :
$posts=Post::with('user')->get();
inside your user model :
class User extends Model
{
public function posts(){
return $this->hasMany('App\Model\Post');
}
}
now you want to get a user with all posts :
$user=User::where('id',$id)->first();
$user_posts=$user->posts;

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?

Limits to multiple Eloquent relationships ?

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.

Resources