Laravel Relationships: hasManyThrough, belongsTo, belongsToMany - laravel

Heyy, I have a Laravel project here, can u guys help me with this question about relationship?
I have the following database structure:
users
id
name
email
password
event
id
description
city_id
block_range
id
event_id
user_block_ranges
user_id
block_range_id
Explanation
users: A normal user authentication table. (has a belongsToMany relationship with user_block_ranges)
event: Stores event info. (has a hasMany relationship with block_range)
block_range: Save blocks of time of event. (has a belongsTo relationship with event)
The real question is: how do I get all the events of the user? Through the user_block_ranges then block_range relationship? Maybe using hasManyThrough?
Thanks in advance.

I believe your models look like this:
User model
class User extends Model
{
public function blockRanges()
{
return $this->belongsToMany('App\BlockRange', 'user_block_ranges', 'user_id', 'block_range_id');
}
}
Block Range model
class BlockRange extends Model
{
public function event()
{
return $this->belongsTo('App\Event');
}
}
To get all events of the user you can do this:
$user = App\User::find(1);
$events = array();
foreach ($user->blockRanges as $block_range) {
$events = $block_range->event;
}

Related

How to get only selected column in a child related model?

I have two models, User and Post, where a User can have multiple Post models. In my application, I only want to retrieve the title column from the related Post model when querying for a User. Here is my current code:
class User extends Model
{
public function posts()
{
return $this->hasMany(Post::class);
}
}
class Post extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
Here is what I have tried to retrieve the title column for the related Post models:
$user = User::with('posts:title')-\>get();
However, this retrieves all the columns for the Post model. How can I modify my code to only retrieve the title column for the related Post models? Thank you!
try this
$user = User::with(['posts' => function ($query) {
$query->select('title');
}])->get();
If you want to get the data with selected column you also need to pass the FK to identify its relationship.
The example below tells the the post also need the user_id column to identify the relationship between POST and USER model
$user = User::with('posts:title,user_id')->get();

How get users from section table ? laravel

The idea is that I have relation between two table's section and user
the section_id exist in users table it relation with id section
SO for ex : section_id = 2 > want to bring all users belongs to id section
My code here use id from url and I don't want to do this I want without id bring all users :
public function getAllUsers($id)
{
$data = User::where('section_id',$id)->get();
}
If I'm understanding you correctly, you want to get all the users for a particular Section that have the relationship to that section.
Assuming you have the relationship set up correctly on the Section model:
public function users() {
return $this->hasMany('App\User');
}
I suggest you go about this 'backward' and just pull the users from the Section model itself (eager loading allows one query):
$section = Section::with('users')->first();
$usersForThisSection = $section->users;
If you setup a One to Many relationship you can say things like: $user->section to return the section a user belongs to...and $section->users to get a collection of all the users in a section -- the getAllUsers() is redundant in this case.
Make sure your User and Section models contain these methods. Sounds like your migration was setup properly if you have a section_id column on your users table.
More info on one-to-many here: https://laravel.com/docs/5.8/eloquent-relationships#one-to-many
// app/User.php
class User extends Model
{
public function section() {
return $this->belongsTo('App\Section');
}
}
// app/Section.php
class Section extends Model
{
public function users() {
return $this->hasMany('App\User');
}
}
Test out your relationships in php artisan tinker like so...
$user = User::find(1);
$user->section
$section = Section::find(1);
$section->users
you need a unique identifier to receive section_id's users. receive it from url(get) or ajax(post) . if you worry about users access then use "auth"

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();

Polymorphic relations in Laravel

Please, Help me!
I have User model and migration: id, login, password.
3 roles and models (Admin, Teacher, Student) and here more information about user. And user can get several roles (he can be admin and teacher)
And one polymorphic model Role with columns:
user_id
roleable_id
roleable_type
For example, User::find(1)->roles;
And i'd like that result shows two model (admin and teacher).
Pleasee, help me))
You could try to eager load the models by using this in your User model https://gist.github.com/thisdotvoid/3022fee8afa53e45a6b89da3f16b3815. Add the required morph functions and then add three functions to the user model similar to this one (change the name and the model name accordingly):
public function admin()
{
return BelongsToMorph::build($this, 'App\Admin', 'rolable');
}
Then create a mutator function like
function getRolesAttribute()
{
$roles = new Collection();
$roleNames = ['admin', 'teacher', 'student'];
foreach ($roleNames as $role) {
$hasRole = $this->{$role};
if ($hasRole) {
$roles->push($role);
}
}
return $roles;
}

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