Laravel DB and Eloquent design - laravel

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') }

Related

How to setup relationship between 2 table which has both one-to-many and many-to-many relationship?

I have a Users table and an Events table.
It's has one-to-many relationship.
Each user can create many event.
Each event belongs to one user.
Also, it has many-to-many relationship.
Each user can join as many event as they want.
Each event can be joined by many user.
This needs pivot table.
Now, I'm stuck.
This is event model.
public function user(){
return $this->belongsTo('App\User');
}
public function users(){
return $this->belongsToMany('App\User')
->withTimestamps();
}
This is user model.
public function events(){
return $this->hasMany('App\Event');
}
public function events(){
return $this->belongsToMany('App\Event');
}
The problem is in the user model where I can't define multiple function with the same name.
So, is there a way to do this correctly?
Quick answer
Of course you can't have two functions with the same name. In your case, try to use more specific names for each function:
public function createdEvents()
{
return $this->hasMany('App\Event');
}
public function joinedEvents()
{
return $this->belongsToMany('App\Event');
}
Recommendation
You can use a single many-to-many relationship to manage both relations with Pivot information:
users table
id
username
...
events table
id
name
...
event_user table
user_id
event_id
is_creator (default FALSE, unsigned integer)
...
Then when creating an event, relate the user and event objects and set the is_creator field to TRUE.
So in your User model:
app/User.php
public function events()
{
return $this->belongsToMany('App\Event')->withPivot('is_creator');
}
Then in your controller when you want to create an event:
app/Http/Controllers/SomeCoolController.php
public function store(CreateEventRequest $request)
{
// Get your event data
$data = $request->only(['your', 'event', 'fields']);
// create your object
$newEvent = Event::create($data);
// create the relationship with the additional pivot flag.
auth()->user()->events()->attach($newEvent, ['is_creator' => true]);
// the rest of your code.
}
And when a user want to 'join' an event:
app/Http/Controllers/SomeCoolController.php
public function join(JoinEventRequest $request)
{
// Get the event
$event = Event::find($request->event_id);
// relate the ev
auth()->user()->events()->attach($newEvent, ['is_creator' => false]);
// or just this, because its already set to false by default:
// auth()->user()->events()->attach($newEvent);
// the rest of your code.
}
It seems like it's many to many relationships between User and Event so there will be pivot name like user_event
user model
public function events() {
return $this->belongsToMany('App\Event')->using('App\UserEvent');
}
Reference: https://laravel.com/docs/5.7/eloquent-relationships#many-to-many

How to create relationship in Laravel 5 which will collect records of own model mentioned in pivot table?

I have 3 tables users, companies and pivot table with user_id, company_id.
I can't get users, which belongs to my company inside User model.
Tried like
belongsToMany('App\User','companies_users','company_id','user_id' );
but I get relation with wrong users.
Since you are having a belongsToMany relationship between the User and Company, the User belongs to more than one Company. To get users of the companies of a particular User will not be straight forward. If you are sure that is exactly what you want, then do this:
//inside the User model
public function companies()
{
return $this->belongsToMany('Company');
}
//inside the User model
public function companiesusers()
{
$users= new Illuminate\Database\Eloquent\Collection;
foreach($this->companies as $company)
{
$users = $users->merge($company->users->get());
}
return $users->unique();
}
//inside the Company model
public function users()
{
return $this->belongsToMany('User');
}
Then you can get a user's companiesusers like so:
User::first()->companiesusers();

A department can belongsToMany, but a user can only belongTo department? How to pivot this correctly?

So im trying to figure out how to use pivot tables in Laravel. And I have tried to read and understand the documentation. And I cannot understand why a user just can't balongTo a "department". I don't want a user to belongToMany "departments".
Departments model
public function users()
{
return $this->belongsToMany(User::class, 'department_user', 'user_id', 'department_id');
}
And for the user model, I want something like
public function department()
{
return $this->belongsTo(Department::class);
}
But Laravel reports null. Because department_id doesn't exist in the users row? How can I reverse this pivot table lookup, with belongsToMany and belongsTo?
I think you're getting confused with your relationship types. If I understand you correctly:
A Department hasMany Users.
A User belongsTo a Department.
This one-to-many relationship type does not need a pivot table and can be written as such:
class Department extend Eloquent
{
public function users()
{
return $this->hasMany(User::class);
}
}
class User extend Eloquent
{
public function department()
{
return $this->belongsTo(Department::class);
}
}
This would require that the users table have a department_id foreign key.

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 4 - Display username based on ID

I have a posts and a users table.
In the posts table, i have a posts_author which is the ID of the user from the users table.
Is there an easy way to display the email address of the user, which is in the users table?
Cheers,
As long as you've set your relationships up it should just be a simple query.
http://laravel.com/docs/eloquent#relationships
Look at the one to many relationships.
(1 User, Multiple posts)
Remember to set the inverse of the relationship up also
If your model has the right relationships then should be as simple as $post->author->email().
You must tweak the author relationship because Eloquent assumes the key will be named author_id.
// Post
public function author() {
return $this->belongsTo('Author', 'posts_author');
}
// Author
public function posts() {
return $this->hasMany('Post');
}
Remember to use eager loading in case you are retrieving emails from more than one post object, or you will end up with n+1 queries.
Providing that you've configured the relationships properly, it should be pretty easy.
Post Model:
class Post extends Eloquent
{
protected $table = 'posts';
public function author()
{
return $this->belongsTo('User', 'posts_author');
}
}
Then User Model:
class User extends Eloquent
{
protected $table = 'users';
public function posts()
{
return $this->hasMany('Post', 'posts_author');
}
}
Then when loading the post you can do the following.
$post = Post::with('author')->find($id);
This will tell Eloquent to join on the users table and load the user data at the same time. Now you can just access all of the user information like this:
$post->author->username;
$post->author->email;
$post->author->id;
// etc etc
Obviously this is just a skeleton, but the assumption is that you have the rest setup.

Resources