Eloquent belongsTo relationship - laravel-4

in a
public function parent()
{
return $this->belongsTo('Parent', 'parent_id');
}
relationship $child->parent results in NULL whereas testing $child->parent()->first() works as intended.
Is that how it's supposed to be or is there something wrong?

I think you need the local key to work.
Try this: return $this->hasMany('Comment', 'foreign_key', 'local_key');

Related

Relationship between table is not working

I have two tables user and profile. Profile table had user_id as foreign key. I have related the two tables.
In tinker I can see that relation is made but in code its not fetching the details from other table.
I have also tried
return $this->belongsTo('User::class');
User Model
public function profile() {
return $this->hasOne('Profile');
}
Profile Model
public function user() {
return $this->belongsTo('User');
}
I see two things that are not completely right.
In tinker to obtain the profile of user insert this lines:
$user = User::find([user_id]);
And then :
$user->profile();
If you want to associate the ::class you should use:
return $this->belongsTo(User::class);
If you want to use the string association should use:
return $this->belongsTo('App\User');
return $this->hasOne('App\Profile');
Another tip is every time you change a controller you have to close and open tinker again
Try to specify keys for hasOne and belongsTo method as below:
$this->hasOne('Profile', 'foreign_key', 'local_key');
$this->belongsTo('User', 'foreign_key', 'local_key');
Look also on one to one relation:
https://laravel.com/docs/6.x/eloquent-relationships#one-to-one

Why Eloquent HasMany return an empty collection?

Hi why i get an empty collection when i use $user->posts as property. However i do a get collection when i use $user->posts() as function.
public function user(){
return $this->belongsTo(User::class);
}
public function posts(){
return $this->hasMany(Post::class);
}
public function index(User $user){
dd($user->posts);
return view('home', compact('user'));
}
#foreach($user->posts as $post)
<p>$post->title</p>
<p>$post->body</p>
#endforeach
result
Collection {#1102 ▼
#items: []
}
The first method (user) should be in your post model.
The second method (posts) should be in your user model.
Check your database and see if the posts table has a column named user_id.
Check your database and see if the user_id column has a valid value (according to the users table.
Also make sure your route has {user} in it. Something like this:
Route::get('home/{user}', 'Cotroller#method')
User model:
public function posts(){
return $this->belongsTo(User::class);
}
Post model:
public function user(){
return $this->hasMany(Post::class);
}
And make sure you have user_id column on your post table

Eloquent's "with" doesn't return anything for one relationship, but does for other

I have a Member model in my Laravel application, and in the model:
public function active_memberships() {
return $this->hasMany(MemberMembership::class, 'member_id', 'id')->where(function($query) {
$query->where('ends_at', '>', Carbon::now());
});
}
public function promo_code() {
return $this->hasMany(MemberPromoCode::class, 'member_id', 'id');
}
Both the member_memberships and member_promo_codes tables have member_id as a foreign key. However, if I do this:
$member = Member::with(['active_memberships','promo_code'])->find($id);
I get the active_memberships array in $member, but not promo_code.
So, $member['active_memberships'] prints out an array., but $member['promo_code'] gives an error:
Undefined index: promo_code
What am I missing here?
Try changing your relationship methods to these:
public function active_memberships() {
return $this->hasMany('\App\MemberMembership', 'member_id')->where(function($query) {
$query->where('ends_at', '>', Carbon::now());
});
}
public function promo_code() {
return $this->hasMany('\App\MemberPromoCode', 'member_id');
}
You don't need to pass the third parameter as id because that is by default and try to give the relation using the namespace as that is the most basic way to define relations.
See if Controller query works then?

How to add a condition to a eloquent relation

This is the case I have
$user = User_picture::where('is_main','=',1)->where('user_id','=',Auth::user()->id);
This means a user has many pictures but there is only one picture that has is_main value 1.
I tried this.
public function active_picture()
{
return $this->hasMany('App\User_picture')->find($this->is_main);
}
This doesn't return anything but an error that says it should be an object. Can anyone help me out with the case?
HasMany is meant to return a collection since it is a one to many relationship method.
If you only want to return one result, you should use HasOne with conditions. To define conditions, you use where() not find(). Find() is only used to match the model's primary key.
public function active_picture()
{
return $this->hasOne('App\User_picture')
->where('is_main', 1);
}
You could declare an accessor like:
In User model:
// declare relationship:
public function pictures()
{
return $this->hasMany(Picture::class);
}
// declare accessor:
public function getMainPictureAttribute()
{
return $this->pictures()->where('is_main', 1)->first();
}
So you can do this:
auth()->user()->main_picture ...

hasOne relationship and associate()?

I have this relationship :
public function company(){
return $this->hasOne('App\Models\User','personal_users_business_users', 'user_id', 'business_user_id');
}
When i try this:
$user->company()->associate($business_user_id);
Im getting this error:
Call to undefined method
Illuminate\Database\Query\Builder::associate()
I have pivot table personal_users_business_users and it has user_id, business_user_id, approved
And now i want to insert in that pivot table business_user_id. What im doing wrong?
Your relationship should be like this:
public function company()
{
return $this->hasOne(User::class);
}
User is the model you want to connect with,
and you should call the relationship like this:
$user->company->business_user_id;
$user must be the Model you have the relationship function in.
company is the function and the business_user_id the field you want to get
associate() is a method of the belongsTo relationship, but it looks like from the above you are trying to call it via the hasOne relationship.
UPDATE
You can create a function in your App\Models\User class
public function company() {
return $this->belongsTo('MODEL_OF_COMPANY', 'foreign_key', 'owner_key', 'relation');
}
then call $this->company()->associate($company)

Resources