I have User and Project models.
The relationship is many to many.
public function projects()
{
return $this->belongsToMany('App\Project')->withPivot('id');;
}
And in Project Model I have :
public function users()
{
return $this->belongsToMany('App\User')->withPivot('id');;
}
Now what I am doing :
$projectsAsFreelancer = App\Project::where('assignedTo',$id)->get();
What i want is to get the username from the users table of the user, Who have posted the project. The Project means projects table have the forign_key->employeer_id.
Currently $project->pivot->username gives me error.
pivot table name is project_user.
What i am missing ?
$project->pivot->username requires the username field in your pivot table. ->withPivot('id'); is only required if you wish to get id column of the pivot table, $project->pivot->id wil give the value.
If you want to get username from users table you don't require pivot.
$projectsAsFreelancer = App\Project::where('assignedTo',$id)->get();
foreach($projectsAsFreelancer as $project)
{
echo $project->name;
foreach($project->users as $user)
{
echo $user->username;
}
}
Don't use get(). It could not fetch the relations. You could use first() or find() (if you want to select with primary key)
$projectsAsFreelancer = App\Project::where('assignedTo',$id)->first();
foreach ($projectsAsFreelancer->users as $user) {
//var_dump($user->username);
}
Related
hi im using laravel 7 i've the relation in the user model called get_journal_entry_lines
public function get_journal_entry_lines()
{
return $this->hasMany('App\Models\Journal_entry_line','user_id','id')->orderBy('date','asc');
}
sometimes the user in column called user_id and sometimes on other column called partner_id
so is it possable to do something like this in laravel
public function get_journal_entry_lines()
{
return $this->hasMany('App\Models\Journal_entry_line','user_id','id')->orderBy('date','asc')->orWhere('partner_id','=','id');
}
get Journal_entry_line from columns user_id and partner_id at same relation .
Can't you just create 2 different relations?
For example, you could use the one below for your users:
public function get_journal_entry_lines_for_users()
{
return $this->hasMany('App\Models\Journal_entry_line','user_id','id')->orderBy('date','asc')->orWhere('partner_id','=','id');
}
and this one for your partners:
public function get_journal_entry_lines_for_partners()
{
return $this->hasMany('App\Models\Journal_entry_line','partner_id','id')->orderBy('date','asc');
}
In my project there are three table like (teacher, attendance,user) and i have define the relationship in there model. in teacher table relation with both attendance and user but user has no relationship with attendance when i want to fetch data it show an error like Property [attendance_status] does not exist on this collection instance. how can i solve this problems.
This is User model
public function teacher() {
return $this->hasOne('App\Teacher');
}
this is Teacher model
public function attendance() {
return $this->hasMany(Attendance::class,'teacher_id','user_id');
}
this is attendance model
public function teacher() {
return $this->belongsTo(Teacher::class,'teacher_id','user_id');
}
and in my attendance controller I define like this
$staffAttendances = Teacher::with(['attendance','user'])->get();
foreach ($staffAttendances as $attd) {
echo $attd->user->first_name .'<br>';
echo $attd->designation.'<br>';
echo $attd->attendance->attendance_status.'<br>';
}
Try
$attd->attendance[0]->attendance_status
I have the following schema set up:
users:
id
departments:
id
department_user:
id
department_id
user_id
I also have the following relationships set up:
User Model
public function departments()
{
return $this->belongsToMany('App\Resources\Eloquent\Models\Department', 'department_users');
}
Department Model
public function users()
{
return $this->belongsToMany(User::class, 'department_users');
}
For some reason, when I am trying to access through the user model $user->departments, it doesn't work - but $department->users does.
Outputting the eloquent query is as follows:
select `departments`.*, `department_users`.`user_id` as `pivot_user_id`, `department_users`.`department_id` as `pivot_department_id` from `departments` inner join `department_users` on `departments`.`id` = `department_users`.`department_id` where `department_users`.`user_id` is null
I can't seem to figure out why it is looking to see if department_users.user_id is null, when it should be looking for the user's id.
Any ideas?
Why don't you set up your models like it is suggested in the documentation here:
So your models would look something like this:
User Model
public function departments()
{
return $this->belongsToMany('path\to\your\model\Department');
}
Department Model
public function users()
{
return $this->belongsToMany(path\to\your\model\User);
}
Eloquent will join the two related model names in alphabetical order.So you don't need extra arguments when defining your relationship and Laravel also by default, makes model keys present on the pivot object. And then you can do something like this:
$department = path\to\your\model\Department::find(1);
foreach ($department->users as $user) {
echo $user;
}
For some reason, if I make the relationship the following - it works.
return $this->belongsToMany(Department::class, 'department_users')->orWhere('department_users.user_id', $this->id);
If anyone knows why, please let me know
I am using a pivot table genre_user to relate user to genre.
table contains the following fields
id
user_id
genre_id
Following are the model definitions
User.php
public function genres() {
return $this->belongsToMany('App\Genre');
}
Genre.php
public function artists() {
return $this->belongsToMany('App\User');
}
I am getting the results as a collection when I use the following code
$user = auth()->user();
dd($user->genres);
I want to show the selected genres in a dropdown field of genres. Is it possible to get only the current users genre_id as an array from the pivot table without using a foreach loop.
I think what will help you achieve this behavior is the lists() method.
Try something like
$user_genres = auth()->user()->genres()->lists('name','id');
If you are using Forms & HTML package you can just do
{!! Form::select('genres',$user_genres,null) !!}
And here is your dropdown
More info here (scroll down to "Retrieving A List Of Column Values")
A user should have one genre.
Therefore, your models should contain the following relations:
User.php
public function genre() {
return $this->hasOne('App\Genre');
}
Genre.php
public function artists() {
return $this->belongsToMany('App\User');
}
I'm trying to create a Friendship system with Laravel (I'm starting with it) but I'm blocked with relationships. Here's the thing : there is one table Users and one table Friends which contains the following columns :
friends: id, user_id, friend_id, accepted.
It looks like a Many to Many so here's what I set on User class :
class User extends Eloquent {
function friends()
{
return $this->belongsToMany('User');
}
}
But when I try a :
$friends = User::find($id)->friends()->get()
I have this error :
Base table or view not found: 1146 Table 'base.user_user' doesn't exist
I would like to get a list of the Friends of a user, no matters if the user sent the invitation or received it. So the user can ba on user_id or on friend_id and then I retrieve the data of the other user depending of that column.
Any idea? Thank's!
EDIT : Here's the code I use :
$usersWithFriends = User::with('friendsOfMine', 'friendOf')->get();
$user = User::find(Auth::id())->friends;
foreach($user as $item) {
echo $item->first()->pivot->accepted;
}
tldr; you need 2 inverted relationships to make it work, check SETUP and USAGE below
First off the error - this is how your relation should look like:
function friends()
{
return $this->belongsToMany('User', 'friends', 'user_id', 'friend_id')
// if you want to rely on accepted field, then add this:
->wherePivot('accepted', '=', 1);
}
Then it will work without errors:
$user->friends; // collection of User models, returns the same as:
$user->friends()->get();
SETUP
However you would like the relation to work in both ways. Eloquent doesn't provide a relation of that kind, so you can instead use 2 inverted relationships and merge the results:
// friendship that I started
function friendsOfMine()
{
return $this->belongsToMany('User', 'friends', 'user_id', 'friend_id')
->wherePivot('accepted', '=', 1) // to filter only accepted
->withPivot('accepted'); // or to fetch accepted value
}
// friendship that I was invited to
function friendOf()
{
return $this->belongsToMany('User', 'friends', 'friend_id', 'user_id')
->wherePivot('accepted', '=', 1)
->withPivot('accepted');
}
// accessor allowing you call $user->friends
public function getFriendsAttribute()
{
if ( ! array_key_exists('friends', $this->relations)) $this->loadFriends();
return $this->getRelation('friends');
}
protected function loadFriends()
{
if ( ! array_key_exists('friends', $this->relations))
{
$friends = $this->mergeFriends();
$this->setRelation('friends', $friends);
}
}
protected function mergeFriends()
{
return $this->friendsOfMine->merge($this->friendOf);
}
USAGE
With such setup you can do this:
// access all friends
$user->friends; // collection of unique User model instances
// access friends a user invited
$user->friendsOfMine; // collection
// access friends that a user was invited by
$user->friendOf; // collection
// and eager load all friends with 2 queries
$usersWithFriends = User::with('friendsOfMine', 'friendOf')->get();
// then
$users->first()->friends; // collection
// Check the accepted value:
$user->friends->first()->pivot->accepted;
It's oviously a problem in your DB and also definition of the relation. Many-to-Many relation type expects you to use and intermediate table. Here's what you have to do :
Create a user_friend (id, user_id, friend_id) table in your schema.
Remove unnecessary fields from user and friend tables.
Create proper foreign keys . user.id-> user_friend.user_id , friend.id -> user_friend.friend_id
Better define full relation on the User and Friend models,
for example :
class User extends Eloquent {
function friends()
{
return $this->belongsToMany('User', 'user_friend', 'user_id', 'friend_id');
}
}
You can read much more in Laravel docs, HERE