1 to 1 and 0 to many relationship Laravel not working - php

I am struggling with an eloquent request. Let me explain what I want to do:
I have two models: User and Item
One User can have many Item and one Item belongs to One user.
I wrote the two method for this relation in my models as followed:
class Item extends Model
{
public function user() {
return $this->belongsTo(User::class);
}
}
class User extends Model {
public function items() {
return $this->hasMany(Item::class, 'items', 'user_id', 'user_people_id');
}
}
I try to access to the items from my controller its user's relation with:
public function index()
{
$items = Item::with('user')->get();
dd($items);
FYI: I seeded my items table with 10 items and my user table with 4 users:
items table:
users table:
My problem is that in the when I check my query with dd() here is what I get: Only the 4 first items get the relation, the others 6 return a null value
Relation working:
Relation returning null:
Thank you for helping me!

According to Laravel doc, hasMany relationship parameters are the following:
return $this->hasMany(Myclass::class, 'foreign_key', 'local_key');
So try to change your relationship in your User class like that
// change this
return $this->hasMany(Item::class, 'items', 'user_id', 'user_people_id');
// to this
return $this->hasMany(Item::class, 'user_people_id', 'id');

The easiest solution would be to rename your foreign key to user_id. That is what Laravel expects, so you won't need to deal with extra arguments in your hasMany() functions.
If you can't do that I think this'll work: return $this->hasMany(Item::class, 'user_people_id');.

Please try to add all in your query to see if it will work:
Update
public function index()
{
$items = Item::all();
dd($items);
}

Related

Laravel : Use Pivot table to get group with their respective roles

I'm trying to get All roles in a user group in eloquent style.
//this function is defined in the ModelUserGroup
public function roles(){
return $this->hasMany(ModelGroupRole::class, 'group_id','id');
}
I'm trying to get all roles like this:
ModelUserGroup::with('roles')->get(),
I also tried ->hasManyThrough but it is not working for me.
I need all roles data like id,name, etc. using with.
Looks like you need a belongsToMany relationship.
In your UserGroup model.
public function roles()
{
// Assuming your role model is named ModelRole...
return $this->belongsToMany(ModelRole::class, 'group_role', 'group_id', 'role_id');
}
Now you can do the following:
$group = ModelUserGroup::with('roles')->first();
dd($group->roles); // will be a collection of ModelRole's
Answered on my phone so there may be syntax errors.
As stated here in the many to many section, you have got to define the relationships as the follwing:
in User_Group :
public function roles(){
return $this->belongsToMany('App\Pathto\Role', 'group_role','group_id','role_id');
}
in Role:
public function user_groups(){
return $this->belongsToMany('App\Pathto\UserGroup', 'group_role', 'role_id', 'group_id');
}
Edit: ModelUserGroup::with('roles')->get() should work just fine then.
(of course, change pathto with your path to the models.)

Laravel relationship returns NULL

I'm try to get relations via laravel Eloquement model. I'm have two models ex Books.php and Magazine.php
in Books.php i have
public function magazines()
{
return $this->hasMany('App\BOOKS', 'id', 'id');
}
Then i'm try to return all magazines, which relate with books
$books = Book::find(123);
$magazines = $books->magazines()->get();
return $magazines;
but i'm have NULL magazines! When i'm add
$magazines = $books->magazines()->toSql();
i'm see this select: select * from "MAGAZINE" where "MAGAZINE"."ID" is null and "MAGAZINE"."ID" is not null - what is it? Why laravel model put "is null and is not null"?
Notice, if i'm change
public function magazines()
{
return $this->belongsToo('App\BOOKS', 'id', 'id');
}
Select would be like this: select * from "MAGAZINE" where "MAGAZINE"."ID" is null
Anyone know, what is this?
There are several problems in your code:
HasMany takes as first parameter the related model class so in your case is pointless to pass App\Book. You should pass App\Magazine assuming that your magazine model is called Magazine
you are not saying to the HasMany relationship what is the name of the foreign key on your magazines table.
That should do the job
public function magazines()
{
return $this->hasMany('App\Magazine', 'book_id', 'id');
}
IMHO i suggest you to read the Laravel documentation before posting here, there are a lot of examples that will explain to you how to work with relationships and database tables. Take a look to One to Many relationships.
EDIT
You can omit the ->get() on the relationship and simply fetch your magazines doing
$magazines = $books->magazines;
You should try this:
Please change and try:
public function magazines()
{
return $this->hasMany('App\MAGAZINE');
}

Laravel 5 – get particular many to many relation based on model and related model ID

I've got Tag and Attendee Eloquent models, they are in many-to-many relation. Pivot table has also two more attributes – value_int and value_string. My Attendee model looks like this:
class Attendee extends Model
{
public $timestamps = false;
protected $fillable = [
'event_id'
];
public function tags() {
return $this->belongsToMany('App\Models\Tag', 'attendee_tag', 'attendee_id', 'tag_id')
->withPivot(['value_string', 'value_int']);
}
public function scoreTagValue($tag_id) {
return $this->tags->where('tag_id', '=', $tag_id)->first();
}
}
What I want is to obtain pivot values based on Attendee model and variable tag_id, so I've written scoreTagValue function, but it always returns null and I don't know why :( I'm calling it this way:
$attendee->scoreTagValue($tag_id). Thanks for your help :)
You need to access the relation, not the property:
public function scoreTagValue($tag_id) {
return $this->tags()->where('tag_id', '=', $tag_id)->first();
}
Also, according to the docs, withPivot() does not take an array, so:
->withPivot('value_string', 'value_int');

Laravel 5.4 relationship

Hi I need to display users items from table name Items.
I have 3 models.
User model:
public function userItem()
{
return $this->hasMany('App\UserItem', 'item_id');
}
UserItem model:
public function user()
{
return $this->belongsTo('App\User', 'user_id');
}
What to write to Item Model to make this relationship successful. So I could display items from items table.
If I now do this:
I get info from user_items table from DB.
when I do this #foreach(Auth::user()->userItem as $item) I get this:
Column not found: 1054 Unknown column 'user_items.user_items' in
'where clause'
I think you want to use many to many relation
you have 2 models User and Item
and 3 tables : -users -items -user_items
User Model should be like this:
public function userItem()
{
return $this->belongsToMany('App\Item','user_items','user_id','item_id');
}
and Item Model:
public function user()
{
return $this->belongsToMany('App\User','user_items','item_id','user_id');
}
and you need a table that you named it user_items
and you dont need to define userItem model you can remove relations in this model
in your blade use this code:
#foreach(Auth::user()->userItem as $item)
You are exhibiting a many-to-many relatioship, and yet using methods for one-to-many relationships. For a many to many relationship, use the following code in your models:
//user model:
public function userItem()
{
return $this->hasMany('App\UserItem', 'user_items', 'user_id', 'item_id');
}
//userItem Model:
public function user()
{
return $this->hasMany('App\User', 'user_items', 'item_id', 'user_id');
}
For a many-to-many relationship, you need a hasMany method on both your models.
For information on the parameters to the hasMany method as well as other information on many-to-many relationships, please read the documentation on many-to-many relationships: https://laravel.com/docs/5.4/eloquent-relationships#many-to-many
Hope this helps.

Laravel 5.2 hasManyThrough relationship issue

I have 3 tables: orders, codes, events
I want to be able to pull all events that an order has, but there's an intermediary table that acts as a pivot table. I've been trying to use hasManyThrough and belongsToMany (along with withPivot) without any luck.
Examples:
public function events()
{
return $this->belongsToMany('events'); // tried this, fails
return $this->hasManyThrough('events', 'codes'); // tried this, fails
return $this->hasManyThrough('events', 'codes', 'event_id', 'id'); // tried this, fails
}
Any pointers would be great!
That's a belongsToMany setup. First, the first parameter is the name of the related class. Second, since your pivot table doesn't follow the Laravel naming conventions, you need to specify the name of the pivot table in your relationship definition:
public function events()
{
// first parameter is the name of the related class
// second parameter is pivot table name
return $this->belongsToMany(Event::class, 'codes');
}
With this setup, you can do:
// get an order
$order = Order::first();
// has all the events related to an order
$events = $order->events;
There are many ways to do this. I will show a one you can get it done.
In Order.php model
public function codes(){
return $this->has('App\Http\Code');
}
In Code.php model
public function orders(){
return $this->belongsTo('App\Http\Order');
}
public function events(){
return $this->hasMany('App\Http\Event');
}
In Event.php model
public function codes(){
return $this->belongsTo('App\Http\Code');
}
Then in you Controller, call them to get required data.
In your case you can do it like below:
$orders = Order::with(['codes' => function($q){
$q->with('events');
})->get();
May be you can get them with nested manner(not sure about this because i didn't tried before posting):
$orders = Order::with('codes.events')->get();
put return $orders; in your controller to see the query.
Enjoy!

Categories