Eloquent Relationship in the same model in Laravel - laravel

I am using User model to fetch user_type = 5. They are associated with user_type = 3 in vendors table. I want to make a relationship in User or Vendor model which could help me get users of type 5 along with the associated user of type 3.

To get data with a criteria you can use scopes, like this :
public function scopeMyType($query)
{
return $query->where('user_type ', 3);
}
To use it :
$users = User::myType()->get();
// this will return users with type = 3
You can make self relationship like this:
class User extends \Eloquent {
....
public function hasOne() {
$children = $this->hasMany('Vendor');
}
}

Related

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"

Laravel Eloquent query to check how many siblings student have

i have two tables
**students :**
id
family_id
name
**family :**
id
father_name
father_civil_id
contact_no
both tables are connected using family_id, i want to get how many Brothers/Sisters each students have(with name of sibling) using eloquent.
can you please help me, with controller/model/view.
Let's say you have a Student and Family model. Then you have several ways to do it.
Here are the two easiest ones I can guess with the information you provided.
Without relationship
Controller
Student::where('family_id', $family_id)->get();
HasMany relationship
Family model
class Family extends Model
{
// Since Laravel will expect your table to be 'families'
protected $table = 'family';
public function students()
{
return $this->hasMany(Student::class);
}
}
Controller
$family = Family::with('students')->inRandomOrder()->first();
$siblings = $family->students;
In Students Model:
public function family() {
return $this->belongsTo('App\Models\Family');
}
public function getSiblings() {
return $this->family->students;
}
So you can call it by your students:
$student->getSiblings();

laravel model relationship 5.5

1. users
1. id
2. name
2. categories
1. id
2. category_name
3. user_id
3. posts
1. id
2. post_title
3. category_id
So now I want to show data in my view
like : post_title->category_name->user_name
How to do in laravel query relationship in model
Define the relationships
class Post extends Model
{
return $this->blongsTo(Category::class);
}
class Category extends Model
{
return $this->blongsTo(User::class);
}
Now
$post = with('category.user')->whereId(1)->first(); //1 is my guess
$post->category()->user->name();
Also it seems like a has-many-through relationship though you can access a user's post like this
$user->posts;
For that you need to define:
class User extends Model
{
/**
* Get all of the posts for the user.
*/
public function posts()
{
return $this->hasManyThrough(Post:class, Category::class);
}
}
$Query=DB::select('select posts.post_title,categories.category_name,
users.name from posts,categories,users where users.id=categories.user_id and
categories.id=posts.category_id');
if you dont use DB::
you can use your model
$Query = Users::select('users.name', 'posts.post_title', 'categories.category_name')
->join('categories', function ($join) {
$join->on('categories.user_id', '=', 'users.id')
->join('categories.id', '=', 'posts.category_id');
})
->get();
check spell table name and columns
but if there is duplicate in data it wont work

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

How to perform a has many through statement using laravel eloquent?

Say i have three tables users,users_groups and groups.How can i get the user's groups through the users_groups table?
class User extends Eloquent {
protected $table = 'users';
}
class Groups extends Eloquent {
protected $table = 'groups';
}
class Usergroups extends Eloquent {
protected $table = 'users_groups';
}
As per your request, I've put together a simple example for your specific use case:
The Tables:
Eloquent suggests creating 3 database tables in such a scenario: users, groups and group_user.
The Laravel documentation states that:
The group_user table's name is derived from the aplhabetical order of the related model names.
The group_user table should contain the columns user_id and group_id which will contain the primary keys of group and user entries. The group_user table is what's known as a pivot table.
This conforms to 3NF (if you're interested).
The Models:
The User model should contain the following code:
<?php
class User extends Eloquent {
//...Other code…
public function groups()
{
return $this->belongsToMany('Group');
}
}
The Group model should contain the following code:
<?php
class Group extends Eloquent {
//...Other code…
public function users()
{
return $this->belongsToMany('User');
}
//...Other code…
}
You do not need a UserGroup model as found in your question.
Usage:
In order to retrieve all groups to which a particular user belongs you would do the following:
$user = User::find($user_id);
$user_groups = $user->groups();
Similarly in order to retrieve all users belonging to a particular group you would do the following:
$group = Group::find($group_id);
$group_users = $group->users();
In order to add/remove a user to a group would would do the following:
$user = User::find($user_id);
//Add a user
$user->groups()->attach($group_id);
//Detach a user
$user->groups()->detach($group_id);
Other:
You should read more in the Laravel docs about pivot tables here and about defining foreign keys (for your pivot table) in your migrations here.
I hope that helps!

Resources