skip to Main Content

I tried $this->id but it returns nothing with artisan tinker:

class Part extends Model
{
    ...

    public function inv(): BelongsTo
    {
        echo "foon";
        echo $this->id . "n";
        return $this->belongsTo(
            Inv::class,
            'surv_id',
            'surv_id'
        );
    }
}

2

Answers


  1. If you’re trying to debug relationship, best way is to install laravel/telescope, (https://laravel.com/docs/10.x/telescope) in that way you can view what’s happening when you query your relationship.

    One way to test the primaryKeys when debugging is try putting absurd column name like survvvvvvv_id just to see what’s happening.

    Login or Signup to reply.
  2. As you said in a comment you want to filter Inv model records against user_id in relation. The solution I found is using raw query with relation.

    public function inv(): BelongsTo
    {
    
       return $this->belongsTo( Inv::class,'surv_id','surv_id')->whereRaw('invs.user_id = parts.user_id');
    
    }
    

    Note: Here in whereRaw clause I’m supposing your model Inv::class is using invs database table name. If your database table has a different name then please replace it with the appropriate name according to your table.

    I hope that will work for you.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search