Laravel 6: Fetching data from multiple pivot tables - laravel

I have a funds table that contains funds that are associated with different faculties, institutes, initiatives etc. A fund belongs to many faculties and faculties could have many funds.
I also have a many to many relationship between users and faculty table to make sure that a user can only see the funds associated with specific faculties.
funds table
--------------------
id
name
...
faculties table
--------------------
id
name
...
faculties_funds table
---------------------
id
faculty_id
fund_id
users table
---------------------
id
fname
...
faculties_user
--------------------
id
faculty_user
user_id
Here is how I have defined my relationships:
class Fund extends Model
{
public function faculties(){
return $this -> belongsToMany('App\Faculty');
}
}
class Faculty extends Model
{
public function funds(){
return $this -> belongsToMany('App\Fund');
}
public function users(){
return $this -> belongsToMany('App\User');
}
}
class User extends Model{
public function faculties(){
return $this -> belongsToMany('App\Faculty');
}
}
What I need is to be able to fetch all the funds associated with the faculty that the authorized user is mapped to. I tested the relationships individually and they all work and I can dd the response that also has a relationship array with pivot information but I am somehow not able to get the funds that I want.
Any help would be appreciated in terms of writing a query to get the results preferably without using the raw queries or if I need to redo my database structure.
Here is my code so far:
public function index()
{
$user = Auth::user();
if(Auth::user() -> role == 'superadmin'){
return view('funds.index')
-> with('funds', Fund::all());
}else{
dd( Auth::user() -> faculties); //I can see the faculties associated and also
dd( Auth::user() -> faculties() -> funds ); //doesnt work
}
}
DD Response

Your table naming convention is not as per what Laravel expects: https://laravel.com/docs/7.x/eloquent-relationships#many-to-many
This modified code should return your funds as expected:
class Faculty extends Model
{
public function funds(){
return $this -> belongsToMany('App\Fund', 'faculties_funds', 'falculty_id', 'fund_id');
}
}
class User extends Model{
public function faculties(){
return $this -> belongsToMany('App\Faculty','faculties_user');
}
}
And then call
dd(Auth::user()->with('faculties.funds');

Related

I want to make many to many relationship using laravel Model

I am trying to make many to many relationships b/w three table I don't know how to make that please confirm me my relationship correct or not.
Project table
id | name
user table
id | name
project_assign
id | user_id | project_id
User Model
public function project_assign()
{
return $this->belongsToMany('App\Project_assign','project_assign','user_id','id');
}
project_assign Model
public function user()
{
return $this->belongsToMany('App\User','Project_assign','user_id','id');
}
Project Model
public function project_assign()
{
return $this->belongsToMany('App\Project_assign','project_assign','project_id','id');
}
you don't need to make a relation in project_assign model. only Project and User will have relation,
Project Model
public function users(){
return $this->belongsToMany('App\User','project_assign','project_id','user_id');
}
User Model
public function projects(){
return $this->belongsToMany('App\Project','project_assign','user_id','project_id');
}
In controller you can get like this
User::with('projects')->get();
Project::with('users')->get();

User to User Model: One to Many Relationship on Laravel

I'm doing a project for one of my University courses. But I'm finding it difficult to make relationship between User to User model.
Table: users
id
name
email
type
password
On this table the column type is used for classifying user types.
For example: User can be either distributor or dealer type.
And a distributor may have many dealer
But a dealer may have only one distributor.
To implement this I've created another table and named as dealers_of_distributor.
Table: dealers_of_distributor
id
distributor_id (id of users table)
dealer_id (id of users table)
Although I've used an additional model DelaersOfDistributor, the exact relationship should be between user to user.
How can I make this relationship. I'm confused!
I've tried so far:
Model: User
public function dealersOfDistributor(){
$this->hasMany('App\DealersOfDistributor');
}
Model: DealersOfDistributor
public function user(){
return $this->belongsTo('App\User');
}
The DistributorsController
public function index()
{
$distributors=User::where('type', 'distributor')->get();
$dealers=User::where('type', 'dealer')->get();
$assignedDealers=DealersOfDistributor::all();
return view('distributors.index')->withDistributors($distributors)->withDealers($dealers)->with('assignedDealers', $assignedDealers);
}
In blade file: I've tried $assignedDealer->dealer_id->user->name. But It's showing error.
Model DealersOfDistributor:
public function distributorUser()
{
return $this->belongsTo('App\User', 'distributor_id', 'id');
}
public function dealerUser()
{
return $this->belongsTo('App\User', 'dealer_id', 'id');
}
than you just get the user's data from DealersOfDistributor model, call function dealerUser if you want get user's data from dealer_id, and call function distributionUser if you want get user's data from distribution_id
Controller:
public function index()
{
$assignedDealers=DealersOfDistributor::all();
return view('distributors.index',compact('assignedDealers'));
}
Blade get username:
#foreach($assignedDealers as $assign)
{{$assign->distributorUser->name}}
{{$assign->dealerUser->name}}
#endforeach

laravel display only specific column from relation

I have read a few topics about this, but they managed to solve my problem partially ...
this is my controller
class DeskController extends BaseController{
public function getDeskUsers($deskId){
$user = DeskUserList::where(function($query) use ($deskId){
$query->where('deskId', $deskId);
})->with('userName')->get(array('deskId'));
if (!$user->isEmpty())
return $user;
return 'fail';
}
this is the model
class DeskUserList extends Eloquent {
protected $table = 'desk_user_lists';
public function userName(){
return $this->belongsTo('User', 'userId')->select(array('id','userName'));
}
}
the method getDeskUsers may returns ALL the DeskUserList table records, related with the User table record (on deskUserList.userId = User.id).
practically I want each record returned is composed of:
DeskUserList.deskId
User.userName
eg. [{"deskId":"1","user_name":antonio}]
What i get is
[{"deskId":"1","user_name":null}]
As you can see the user name is a null value...
BUT
if I edit my controller code:
->with('userName')->get(array('userId')); //using userId rather than deskId
then i get
[{"userId":"2","user_name":{"id":"2","userName":"antonio"}}]
By this way I still have two problem:
the userId field is twice repeated
I miss the deskId field (that I need...)
hope be clear, thanks for your time!
You need belongsToMany, no need for a model representing that pivot table.
I assume your models are Desk and User:
// Desk model
public function users()
{
return $this->belongsToMany('User', 'desk_user_list', 'deskId', 'userId');
}
// User model
public function desks()
{
return $this->belongsToMany('Desk', 'desk_user_list', 'userId', 'deskId');
}
Then:
$desks = Desk::with('users')->get(); // collection of desks with related users
foreach ($desks as $desk)
{
$desk->users; // collection of users for particular desk
}
// or for single desk with id 5
$desk = Desk::with('users')->find(5);
$desk->users; // collection of users
$desk->users->first(); // single User model

Laravel DB and Eloquent design

I have read front to back the Eloquent documentation and have looked through many different tutorials (including several hours of nettuts). I have some basic db design questions that relate to the Eloquent model. I would love it if someone could help me make sense.
So this database has Users, Partners, and Events
Users
---------
id
userName
firstName
lastName
Partners
---------
id
user_id
firstName
lastName
Events
---------
id
user_id
partner_id
description
So this is a very basic layout for the purpose of this question. Obviously there will be additional fields placed in each table that give more information (including timestamps, etc).
Each user can have many partners
Each partner has only one user
Each partner has many events
With this basic layout I need to know if I am on the right track in particular with the Events table. There will be times when I need to view all recent events that are associated with the User and also pull data from the partners table (like their firstName and lastName).
So here is my relationship understanding..
User hasMany Partners
Partners hasMany Events
Events belongTo User & belongTo Partner
Will this setup allow me to make simple eloquent calls?
Here are the models as I understand them:
USERS
class Users extends Eloquent {
protected $table = 'Users';
public $timestamps = true;
public function Partners()
{
return $this->hasMany('Partners', 'user_id');
}
public function Events()
{
return $this->hasManyThrough('Events', 'Partners');
}
}
PARTNERS
class Partners extends Eloquent {
protected $table = 'Partners';
public $timestamps = true;
public function Partners()
{
return $this->belongsTo('Users', 'id');
}
public function Events()
{
return $this->hasMany('Events', 'id');
}
}
EVENTS
class Events extends Eloquent {
protected $table = 'Events';
public $timestamps = true;
public function Users()
{
return $this->belongsTo('Users', 'id');
}
public function Partners()
{
return $this->belongsTo('Partners', 'id');
}
}
Depending on your needs you can setup any/all these relations with your schema:
(All simplified to keep it's short, but obviously they are all methods returning relation. Also I include foreign keys, since your examples are wrong, where you put id as 2nd param, and I encourage to use singular names for models)
// User model
partners { hasMany('Partner', 'user_id') }
// events through partners table and partner_id foreign key
partnersEvents { hasManyThrough('Event', 'Partner') }
// events by user_id foreign key
events { hasManyThrough('Event', 'Partner') }
// many to many with events being pivot table
partnersThroughPivot { belongsToMany('Partner', 'events') }
// Partner model
user { belongsTo('User', 'user_id') }
// events through partners table and partner_id foreign key
events { hasMany('Event', 'partner_id') }
// many to many with events being pivot table
usersThroughPivot { belongsToMany('User', 'events') }
// Event model
user { belongsTo('User', 'user_id') }
partner { belongsTo('Partner', 'partner_id') }

How to create relate one table with others using Eloquent ORM

User TABLE:
id -> int
email -> varchar
Tag TABLE:
id -> int
name -> varchar
tags_user TABLE
tab_id ->foreign('tag_id')->references('id')->on('tag');
user_id ->foreign('user_id')->references('id')->on('user');
how to get all tags from specific user?
thanks
You need many to many relationship:
In your user model:
class User extends Eloquent {
public function tags()
{
return $this->belongsToMany('Tag');
}
}
In your Tag model:
class Tag extends Eloquent {
public function users()
{
return $this->belongsToMany('User');
}
}
Then from your controller:
Utilize the many to many relationship.
$tags = User::find(1)->tags;
Important:
Three database tables are needed for this relationship: users, tags, and tag_user. The tag_user table is derived from the alphabetical order of the related model names, and should have user_id and tag_id columns.
Reference:
http://laravel.com/docs/eloquent#many-to-many

Resources