How to query in laravel - php

I have User Model. In user Model I have three user type Admin,Trainer,Student.
I have Job Model, I am storing the the id of trainer ,student and job in pivot table such that one trainer is assigned against one job and many students. Now after storing the ids as foreign key in pivot table.
Now how i can show in a view all trainer, job and assigned students. In la-ravel 5.2
User Model
public function Job_User()
{
return $this->belongsToMany('App\HTTP\Models\Job', 'jobs_users', 'user_id', 'job_id')->with-pivot('job_id');}
public function Trainer_User()
{
return $this->belongsToMany('App\HTTP\Models\Job', 'jobs_users', 'user_id', 'trainer_id')->with-pivot('trainer_id');
}

Related

Laravel hasManyThrough 2 tables

i have two tables as below:
users table:
|id|name|email|password|created_at|updated_at
messages table:
|id|sender_id|receiver_id|message|created_at|updated_at
User model:
public function threads()
{
return $this->hasManyThrough(Message::class, User::class,'id','sender_id');
}
i'm trying retrieve message threads
which isn't working. any help appreciated.
This is an example from laravel eloquent relationship
class Country extends Model
{
public function posts()
{
return $this->hasManyThrough(
'App\Post',
'App\User',
'country_id', // Foreign key on users table...
'user_id', // Foreign key on posts table...
'id', // Local key on countries table...
'id' // Local key on users table...
);
}
}
can you review your code
It seems that you want to retrieve all messages that belongs to a single thread (list of users) using hasMany relationship Through User model, to do that You have to define hasManyThrough inside Thread model not in User model, here is an example:
User:
|id|name|email|password|created_at|updated_at|thread_id
Note thread_id foreign key because thread is a list of users
Thread:
class Thread extends Model {
public function messages() {
return $this->hasManyThrough(Message::class, User::class,'thread_id','sender_id', 'id', 'id');
}
}
Example from laravel doc

Laravel foreign key relation

I've got a strange problem.
I've a users table and a company table. A User belongsTo a company and a company hasMany users.
Both primary keys of the table are id.
In the laravel documentation I read the following:
Additionally, Eloquent assumes that the foreign key should have a
value matching the id column of the parent.
I've got this in my CompanyModel:
protected $table = 'company';
public function users()
{
return $this->hasMany(UserModel::class);
}
When I try this:
$users = CompanyModel::find(1)->users;
dd($users);
It's not working. When I add a foreign key in my relation it works!?:
protected $table = 'company';
public function users()
{
return $this->hasMany(UserModel::class, 'id');
}
This is strange right? What on earth am I doing wrong.
--EDIT--
In my users table I've got a company_id column!
Firstly, I would suggest you rename your Model from CompanyModelto Company and from UserModel to User.
Then ensure you have company_id in your users table. And in your users migration file connect the users table with the companies table as such:
$table->integer('company_id')->unsigned();
$table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
Don't forget to refresh your database.
Then in your models, define the relationships as such:
// User model
// Laravel will automatically identify and use the `company_id` field in your reference
public function company(){
return $this->belongsTo(Company::class);
}
// Company model
public function users(){
return $this->hasMany(User::class);
}
You can then fetch your records in your controller as such:
$user = User::find(1);
$user_company = $user->company; // This might not be necessary in your controller, you can do it in your view
dd($users, $user_company);

Laravel Eloquent relationships and connecting multiple tables

I am trying to build a messaging system for a job site using Laravel 5 and using the Eloquent ORM. The basic premise is that someone posts up a job, and people can respond to that job via a message. The MySQL database is structured as so:
**users table**
id
username
password
**jobs table**
id
user_id (FK with id on Users table)
slug
title
description
**conversations table**
id
job_id (FK with id on Jobs table)
**messages table**
id
conversation_id (FK with conversations table)
user_id (FK with id on users table)
message
last_read
**conversation_user table**
conversation_id (FK with id on Conversation table)
user_id (FK with id on Users table)
When a user finds a job they like, they can send a message to the job creator which will in turn create a new conversation. The newly created conversation id is then used passed to the messages table (alongside the message text itself) and then the conversation_user pivot table is updated with the conversation id as well as the two users who are participating in the conversation (i.e. the person who posted the job and the person sending the message)
I have a model for each table and a summary of the relationships are:
**Job.php**
HasMany - Conversation model
BelongsTo - User model
**Conversation.php**
BelongsTo - Job model
HasMany - Message model
BelongsToMany - User model
**Message.php**
BelongsTo - Conversation model
BelongsTo - User model
**User.php**
HasMany - Job model
HasMany - Message model
BelongsToMany - Conversation model
I have setup a query scope in Conversation.php (my Eloquent model for the Conversations table) which accomplishes the task of displaying the conversations that the authenticated user is participating in:
public function scopeParticipatingIn($query, $id)
{
return $query->join('conversation_user', 'conversations.id', '=', 'conversation_user.conversation_id')
->where('conversation_user.user_id', $id)
->where('conversation_user.deleted_at', null)
->select('conversations.*')
->latest('updated_at');
}
and via my Conversations Repository, I pass on the results of the query scope to my view in my MessagesController like so:
public function __construct(ConversationInterface $conversation)
{
$this->middleware('auth');
$this->conversation = $conversation;
}
public function index()
{
$currentUser = Auth::id();
$usersConversations = $this->conversation->ParticipatingIn($currentUser, 10);
return view('messages.index')->with([
'usersConversations' => $usersConversations
]);
}
and for reference the ConversationInterface is bounded to my ConversationsRepo:
public $conversation;
private $message;
function __construct(Model $conversation, MessageInterface $message)
{
$this->conversation = $conversation;
$this->message = $message;
}
public function participatingIn($id, $paginate)
{
return $this->conversation->ParticipatingIn($id)->paginate($paginate);
}
My question is, given I have what I believe are the right relationships, how I can pass the title of the specific job from the job_id on the conversations table and also the first few words of the last message that was sent within the conversation?
I'm sorry if I'm stating the obvious, but:
Conversation model belongs to Job Model. As you already has the conversation object/id, just do this:
//Controller
$conversation = App\Conversation::find($id);
return view('your view', compact('conversation'));
//View
$conversation->job->title; //the conversation belongs to a job, so requesting the job will return an instance of the job model, which can be asked for the title.
You can also use this on the view to get the first chars from the message:
substr($conversation->messages->last()->message,0,desired lenght);

Laravel select all users that don't have a record

The Issue
I want to get all users who are not managers of a company.
The Relationships
I have a User model, that can have one CompanyGroup. The CompanyGroup can have many Managers. Managers can manage different types of entity, not just CompanyGroups, so this is a polymorphic relationship (however, not directly relevant to my question).
User Model
public function group()
{
return $this->belongsTo('App\CompanyGroup', 'company_group_id');
}
Company Group
public function managers()
{
// This is polymorphic, as a manager can manage different types of entity.
return $this->morphMany('App\Manager', 'managable');
}
Manager
public function user()
{
return $this->belongsTo('App\User', 'user_uuid', 'uuid');
}
What i've tried:
// Get all users, with a relationship of 'group', and the group's 'managers'
$users = $this->user->whereHas('group.managers', function($query)use($group)
{
// Exclude any users where the user's UUID is present in the managers table
$query->where('exp_members.uuid', '!=', 'managers.user_uuid');
})->get();
What this produced
Nothing! It didn't list any users at all. The managers table is currently empty, so it should return all users that have the $group->id assigned to them. If i enter a random record in the managers table, it returns all of the users that have the group id assigned to them, but it doesn't filter out those who are managers.

How to Call function on laravel pivot model

I was trying to get the attendance of each user in a course where the users and the courses have many to many relationship and the attendance table is based on the relationship.
But i couldn't call $user->pivot->attendance(); directly i had to call for the pivot object it self so i can call a function to it as you can see in the answer
The Following is a sample of my Database scheme
I need to run
$users=$course->users;
foreach($users as $user)
{
$user->pivot->attendance(); //error in this line
}
this line gives and error
Call to undefined method
Illuminate\Database\Query\Builder::attendance()
users
id
name
etc
courses
id
name
startDate
endDate
course_user
id
course_id
user_id
payment
regDate
status
userattendance
id
course_user_id
time
inOrOut
And here is the CourseUserPivot Class
class CourseUserPivot extends Eloquent {
protected $table ="course_user";
public function course()
{
return $this->belongsTo('Course');
}
public function user()
{
return $this->belongsTo('User');
}
public function attendance()
{
return $this->hasMany('Userattendance','course_user_id');
}
}
P.S: $user->pivot->payment works and displays the attribute but i cant call methods
You can't use $user->pivot->attendance(); as this calls attendance on the user object not on the pivot object
You will have to fetch the pivot object then call the function like so
CourseUserPivot::find($user->pivot->id)->attendance();
make user that where you used withPivot() function you include the id in the array
like in
class Course{
...
...
public function users()
{
return $this->belongsToMany('Candidate')
->withPivot('id',
'summary',
'status',
'payment'
);
}
}
I was trying to accomplish the same thing, and I was having trouble getting it to work like I wanted until I included the 'id' column of my custom pivot model in the withPivot() method.
For some context, my database structure is:
User table
id
Items Table
id
Sets table (defines a set and the items that can be in an instance of it)
id
Set_User table (Custom Pivot Model, instances of a set created by a user)
id, set_id, user_id
Items_SetUser table (items that belong to a set instance that belong to a user)
item_id, setuser_id
I do this in the controller to get all the sets that user has made an instance of, with custom pivot table data:
$user_sets = \Auth::user()->sets()->withPivot('id', 'name')->get();
And then in blade I can access the items associated with each set instance like this:
$set->pivot->set_items()->count()
Without including 'id' in the call to withPivot(), the above is not possible. Note that set_items() is a method on the custom pivot model that defines a relationship with the items table.

Categories