Laravel Pivot table eloquent relationships - php

Situation: In my laravel project. Below are the 4 Tables. movie_venue is a pivot table of movies and venues. I need to access the showtimes using movie model.
$movie = $this->model->find($movie_id);
$venues = $movie->venues;
Using eloquent relations i can access the venues list. But cant able to create a relationship for getting showtimes from movie model.
| movies | venues | movie_venue | showtimes |
----------------------------------------------------|
| id | id | id |id |
| name | name | movie_id |movie_venue_id |
| .... | .... | venue_id |time |

I assume you're using a One-to-many relationship for Venues to Showtimes?
You could try something like:
foreach ($movies->venues as $venue) {
foreach ($venue->showtimes as $showtime) {
//do something with your showtime.
}
}
By the way: wouldn't it make more sense to start from the venue and than access Showtimes?
UPDATE
Based on your comment, you can try something like this:
$movie = Movie::find($id);
$venues = $movie->venues;
foreach ($venues->showtimes as $showtime) {
// Here you'll get the showtimes per venue.
}

Related

Eloquent Relationships hasMany use loop

I have a database with multiple address records of a user. When I do "pluck()" and "join()" in the foreach path, I get results. But when I type $user->getAddress->address in structures like hasOne, I get the result I want. In short, can I return the loop in hasMany more practically?
Following my code:
user Table
id | name | lastname |
--- -------------- ----------
1 | Rahuel | lastnameRahuel
2 | Dalton Miller | lastnameDalton
adress Table
user_id | address
-------- ---------
1 | 740 Brown Greens Suite
1 | 9906 Cleora Wall Apt.
2 | 53977 Kip Center Apt
UserModel
public function getAddress()
{
return $this->hasMany(Address::class);
}
Controller
$users = User::with('getAddress')->get();
foreach ($users as $user){
echo $user->name;
echo $user->lastname;
echo $user->getAdress->pluck('address')->join(',');
}
You can use the Collection 's implode method to make it look a bit less verbose.
echo $user->getAdress->implode('address', ',');

Multi JOIN Table in Laravel

I have 4 tables below :
track
+----+-----+----------------+-------+
| ID | TID | TITLE | ALBUM |
+----+-----+----------------+-------+
| 1 | AAA | Yesterday | 1 |
| 2 | BBB | Happy | 2 |
| 3 | CCC | Gangname Style | 3 |
+----+-----+----------------+-------+
album
+----+-----+---------+-------+
| ID | AID | TITLE | COVER |
+----+-----+---------+-------+
| 1 | AAA | Album A | 1.jpg |
| 2 | BBB | Album B | 2.jpg |
| 3 | CCC | Album C | 3.jpg |
+----+-----+---------+-------+
track_artist
+----+-----+-----------+
| ID | TID | ARTIST_ID |
+----+-----+-----------+
| 1 | 1 | 1 |
| 2 | 2 | 2 |
| 3 | 3 | 3 |
+----+-----+-----------+
artist
+----+--------+--------+
| ID | NAME | AVATAR |
+----+--------+--------+
| 1 | Taylor | 1.JPG |
| 2 | T-ara | 2.JPG |
| 3 | M2M | 3.JPG |
+----+--------+--------+
I want to get track.TITLE, album.TITLE and artist.NAME base on track.TID (where TID = $XXX) in 4 table above. It's easy when I use raw INNER JOIN MySQL code, but I want to use Eloquent ORM in Laravel. How I can do this ? Thank you.
I have analyzed :
One track belongsTo one Album
One track hasMany track_artist
One track_artist hasOne artist
One track hasMany artist
You can try this
The table should be like this, you need 4 tables
albums(id, title, cover)
artist(id, name, avatar)
tracks(id, album_id, title)
track_artists (id, artist_id, track_id) ManyToMany with tracks
Models
class Album extends Model{
function tracks(){
$this->hasMany(Track::class);
}
}
class Artist extends Model{
function tracks(){
$this->belongsToMany(Track::class, 'track_artists'); //here track_artists table is as pivot table
}
}
class Track extends Model{
function album(){
$this->belongsTo(Album::class);
}
function artist(){
$this->belongsToMany(Artist::class, 'track_artists'); //here track_artists table is as pivot table
}
}
Fetch Data
$track = Track::with('album','artists')->find($trackId);
echo $track->title." - ". $track->album->title;
//now print all artist of this track
foreach($track->artists as $artist){
echo $artist->name;
}
Note: You don't need to create model for track_artists because it is a pivot table for tracks and artists tables. You can insert and update in pivot table using Track or Artist laravel eloquent model. Though if you want you can create it extending Pivot.
Save Data in pivot table
$track = Track::find(1);
$artist = Artist::create(['name' => 'Katy Perry', 'avatar' => 'Katy_Perry.jpg']);
$track->artists()->save($artist); //this save track and artist relation in track_artists pivot table
For details https://laravel.com/docs/5.6/eloquent-relationships#many-to-many
First, your relations ( in my opinion ) need some changes.
One track belongs to one album and one album has many tracks (one to many)
One track has one artist and one artist has multiple tracks (one to many)
One album has multiple artist and one artist has multiple albums(many to many)
You will need a table for the many to many relation with the album id and the artist id
This is an example considering the above points
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class track extends Model{
function album(){
$this->belongsTo(album::class);
}
function artist(){
$this->belongsTo(artist::class);
}
}
class album extends Model{
function track(){
$this->hasMany(track::class);
}
function artist(){
$this->belongsToMany(artist::class, 'my_many_to_many_table');
}
}
class artist extends Model{
function track(){
$this->hasMany(track::class);
}
function album(){
$this->belongsToMany(album::class, 'my_many_to_many_table');
}
}

How to fetch data from multiple tables using Join and where clause

I have written a simple symfony controller where I have two table known as specialtyarea and physician.
this is the basic structure of the table
specialtyarea
-----------------
id | name |
-----------------
1 | dentist |
2 | physician |
Physician table is related to specialtyarea as shown:
Physician
--------------------
id | name | specfk |
--------------------
1 | John | 1 |
2 | Doe | 2 |
3 | Ann | 2 |
I am trying to fetch all the physician where specialty area is 2
This is my snippet of code
public function getAllPhysicianAction($specId)
{
$id = $this->getDoctrine()->getRepository('Bundle:SpecArea')
->find($specId); //assuming that this returns all the id from the specialty table
$allPhysician = $id->getPhysician()->... //kind of lost here
}
How can I retrieve all the records from the physician table using the specialty Id?
I believe that you can just call findBy on your physician repository.
/**
* #Route("/physicians/{specId}", name="getAllPhysician")
*/
public function getAllPhysicianAction($specId)
{
$allPhysician = $this->getDoctrine()
//call the repository of your physician table
->getRepository('Bundle:physician')
->findBy(['specfk' => $specId]);
var_dump($allPhysician);
}
Use the findBy() method of the "physician" repository:
(You didn't post your actual entities so I'm guessing the field/entity names.)
$spec = $this->getDoctrine()->getRepository('Bundle:SpecArea')->find($specId);
$physicians = $this->getDoctrine()->getRepository('Bundle:Physician')->findBy(['spec' => $spec]);
You can also use $specId ID directly instead of fetching the entire entity from database:
$physicians = $this->getDoctrine()->getRepository('Bundle:Physician')->findBy(['spec' => $specId]);
See: Working with Objects - Querying - By Simple Conditions

Laravel count Eloquent belongsToMany related model

I'm new to Laravel, and I got stuck with the following issue:
I have a table for the users, and groups, and a table for connecting them. The general task any user can join any group.
----------------------------------------------
| users | groups | user_groups |
|--------------------------------------------|
| id - int pk | id - pk | id - pk |
| name text | name | user_id - fk |
| email | | group_id - fk |
| phone | | any_attr |
----------------------------------------------
I have the following models:
class User
{
...
public function groups()
{
return $this->belongsToMany(Group::class, 'user_groups')->withPivot(['is_notification_requested']);
}
...
}
class Group
{
...
public function users()
{
return $this->belongsToMany(User::class, 'user_groups');
}
...
}
How do I get all of the groups, with a count of the members? I need the Group model, and a count of the users in the group.
If you're using Laravel 5.3, you can simply add withCount('relationship') as documented here: https://laravel.com/docs/5.3/eloquent-relationships#counting-related-models
Here's an example following your code:
$groups = Group::withCount('users')->get();
Now you can do this:
foreach($groups as $group) {
echo $group->user_count
}

Laravel Has Many Returns a Row even it has a value in relations table

Hi I'm using laravel eloquent for my database query. My Problem is that I can't show the data I wanted to show. I have three tables. Say Users Table, Roles Table and User_Roles table.
Users
id | Name |
1 | John |
2 | Doe |
Roles
id | Name |
1 | Admin |
2 | Employee |
3 | Manager |
User_Roles
id | user_id | role_id
1 | 1 | 2
2 | 1 | 3
3 | 2 | 3
Users has Many Roles that is saved in User_Roles table. My query is "I want to show list of Users that has no Employee roles. In the table I want to show only Doe. How can I make it laravel eloquent.
Hope someone can help!
Define roles relation in User model
public function roles() {
retrun $this->belongsToMany(\Namespace\Role::class);
}
Retrive the role
$role = \Namespace\Role::where('name', 'Employee')->first();
Get the users
$user = \Namespace\User::whereHas('roles', function($query) use ($role) {
$query->where('role_id', '!=', $role->id);
})->get();

Categories