Get last record in related model - activerecord

I have two models: Person and RentedFilm
Person table fields:
id
name
RentedItem fields:
rid
film_id
rent_date
I need to add a new attribute to person model that contains last rent date but I don't know how. Already I have a getRentDates method that hasMany relations in defined inside it.
Would you help me?
Thank you.

Prepare relation like:
public function getLastRentItem()
{
return $this->hasMany(RentItem::class, ['rid' => 'id'])
->orderBy(['rent_date' => SORT_DESC])
->limit(1)
->one();
}
Use it like:
$model->lastRentItem ? $model->lastRentItem->rent_date : null;
*You have to adjust this code, because i didn't saw yours.

Related

How to get the full Relation in Laravel/Eloquent

at the moment i try to learning Laravel and Laravel Eloquent.
I try to solve a problem using relations in Laravel.
I have following Database Structure in my simple Laravel Project.
table players:
id name
table clubs:
id name icon
table players_x_clubs:
player_id club_id
it's a one to many Relation.
Is it possible to get the full club Object who is combined with the player_id?!
The first try was to add this to my Player Model
public function club()
{
return $this->hasOne('App\PlayersXClub');
}
Here, i only get the PlayersXClub Relation with the player_id and the club_id
but i want to get the full club object from the club table, is it possible in a simple way?
any ideas how i have to realize is it correctly?
my solution was this:
public function getClubRelation()
{
$clubRelation = $this->hasOne('App\PlayersXClub')->get()->first();
$club = Club::whereId($clubRelation->club_id)->get()->first();
return $club;
}
With this solution i can do this in my code $player->getClubRelation()->icon
but i don't know if its correct solved or is there a more simple way to resolve it with Eloquent?
You always have access to objects relations. For example:
$player = Player::find(1);
$club = $player->club;
or better
$player = Player::with('club')->find(1);
However, I believe you don't need an additional table. An additional table would result in a many to many relation which doesn't make much sense here.
A player belongs to a single club and a club can have many players. So it's one to many.
You should add a club_id foreign key to players table.
$table->unsignedBigInteger('club_id');
$table->foreign('club_id')->references('id')->on('clubs')->onDelete('cascade');
Player Class
public function club() {
return $this->belongsTo(Club::class);
}
Club Class
public function players() {
return $this->hasMany(Player::class);
}

Get data from eloquent relationship with pivot in laravel

I have 3 DB table.
shows
show_genres
show_show_genre
In my show model, i have:
public function genres()
{
return $this->belongsToMany('App\ShowGenre');
}
So when i do:
$show=Show::find(1);
$show->genres give me collection with all genres that have show_id in shows_genres db.
I have also ShowGenre model where is all genres i have and i use.
Becouse i want to use sync for my genres, that names need to be in database.
But how can i find all shows that have genre id.
I couldn't find any way to get that list. Please help, thanks.
Edit:
You should do this other way around:
Have a model for Genre
your relationship method in Genre model should be
public function shows()
{
return $this->belongsToMany('App\Show', 'shows_genres');
}
belongsToMany accepts two parameters, model and pivot table name if not a standard name.
Your solution:
//Get genre 'strict'
//where could be followed by column name example:whereSlug, whereName
$strictGenre = Genre::whereName('strict')->first();
if($strictGenre)
{
//get shows of this genre
$strictShows = $strictGenre->shows;
}
Read manytomany relationships:
https://laravel.com/docs/6.x/eloquent-relationships#many-to-many
You may use
$show->genres()
->wherePivot('column', value)
->get();
By default Pivot table name must be singular : show_genre (without
plural s)
See docs
Assuming you have this relationship in your genres model
public function shows()
{
return $this->belongsToMany('App\Show', 'shows_genres', 'genre_id', 'show_id');
}
Then you can directly get all shows by genres id like this
$shows = Genre::find($id)->shows;

Selecting specific column in ORM relationship Laravel 5.5

I have an order table with a primary key id and another table trips. I trip can have many orders. I have defined the relationship in this way
public function orders_currency() {
return $this->hasMany('App\Order', 'trip_id', 'id')->select('id', 'converted_currency_code');
}
Although I know that, I have to select id of the order table in order to get the result, that's why I am mentioning to select the id of the order table.
Despite this, I am getting the orders_currency index empty. Which angle am I missing in this case?
Any clue will be appreciated.
Did you set up the model correctly?
You'd do something like this in your model script I suppose
class Trips extends Model
{
public function orders() {
return $this->hasMany('Order');
}
I got the solution by doing this way
public function orders_currency() {
return $this->hasOne('App\Order', 'trip_id', 'id')
->select('trip_id','converted_currency_code');
}
I had to select referencing key in this case.

Laravel relationship between two tables

I'd like your input on this.
I have a Customer_table with a field name. I have another table called Reservation_table with a Customer_name field.
How can I relate them in such a way that I'd see all the bookings by the specific customer?
In Reservation_table you should have a field(foreign key) userid in order ta have a user for each reservation.
You can using primary key - foreign key relationship to relate/join those two tables. Also, instead of having a 'Customer_name' field as your FK referring to 'name' field in 'Customer_table' table, it is better to have an id (unique) generated for each customer; This way you can have an efficient way of uniquely identifying and relating customer across tables; can save space on Database side as well. Hope this helps!
If you want to use eloquent you must first define a relationship.
One reservation belongs to a user. Here is how to define the relationships:
Inside the Reservation model:
public function user()
{
return $this->belongsTo('App/User'); //User model
}
To define the inverse you do the following:
Inside User model:
public function reservations()
{
return $this->hasMany('App/Reservation'); // Reservation Model
}
Now you can do the following in your controller:
$reservations = Auth::user()->reservations;
Now you have all reservations by the currently logged in user.
I am not sure if I got the question right so ask away.

Store relationship with pivot table in laravel 4

Let me explain what i try to achieve.
lets say i have 20 car types for example sport car or family car etc, and 5 cars for example porsche.
When i create a car i have the option to check multiple car types at the same time that belongs to the car and than save it.
I have done some homework and it looks like using a pivot table is the way to go for this inside laravel.
I have this method inside my cars model:
public function types()
{
return $this->belongsToMany('types', 'car_types');
}
And this method inside my types model:
public function cars()
{
return $this->belongsToMany('Car');
}
My tables looks like this:
cars
- id
- name
- created_at
- updated_at
types
- id
- name
- created_at
- updated_at
car_types
- car_id
- type_id
What im trying to do inside my controller is:
$car = new Car();
Car::create( Input::except('types') );
foreach(Input::get('types') as $type)
{
$car->types()->associate($type);
$car->save();
}
This is giving me the following error:
Call to undefined method Illuminate\Database\Query\Builder::associate()
I hope someone can help me out with this.
Thanks in advance.
Well you are almost there. You're right that the two models, Car and Type are in a many to many relation.
In your models you have code that says:
return $this->belongsToMany('types', 'car_types');
and
return $this->belongsToMany('Car');
Error #1:
In the types() method of the Car model as the first parameter you should pass the name of the model, and not the name of the table. So you should change that to something like:
return $this->belongsToMany('Type', 'car_types');
Error #2
In your Car model you're defining the pivot table as car_types, but the pivot definition is missing from the Type model. Either remove , 'car_types' from the types() method in Car model and rename your pivot table to simply car_type, or add , 'car_types' to your cars() method in Type model.
Error #3
Once all the model stuff is set up correctly, you could do in your controller this:
$car = new Car();
$car->name = Input::get('car_name_form_field_name_attribute');
$car->save();
$types = Input::get('types');
$car->types()->sync($types);
Error #4
I'm not sure if this is just a copy/paste error, but your pivot table seems to be missing a primary key field. Every table needs a primary key field, so your car_types table should look something like this:
car_types
id
car_id
type_id
You could also use attach() instead of sync(). More about the difference between these two here
Please try out this code and let us know if it works out.

Resources