Home > Blockchain >  Not able to access connected table in Eloquent when foreignId is different from default
Not able to access connected table in Eloquent when foreignId is different from default

Time:12-07

Here's the problem: I can't access items property in user object and they are connected in an Eloquent relationship (one user can have multiple items), but I named the foreignId column as customer_id as opposed to user_id default as referenced table is users. When I tried to access items property in blade, here is error that showed up on display:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'items.user_id' in 'where clause'

select * from items where items.user_id = 3 and items.user_id is not null

So, it clearly searches for the default foreignId column and not for the one I defined as foreignId for that relationship. Here's relevant part of my code:

Item.php:

public function customer(){
        return $this->belongsTo(User::class,'customer_id');
}



User.php:

public function items(){
        return $this->hasMany(Item::class);
}
public function get_user($user_name){
        return User::where("user_name",$user_name)->first();
    }


Migration for items table:

public function up()
    {
        Schema::create('items', function (Blueprint $table) {
            $table->id();
            $table->foreignId('wine_id')->constrained();
            $table->foreignId('customer_id')->constrained('users');
            $table->integer('quantity');
            $table->timestamps();
        });
    }

UserController.php
...
$user = $user_model->get_user($request->user_name);
            $request->session()->put("user",$user);
...



Blade:

<?php
       $items = session('user')->items;
       $empty_cart = true;
       foreach($items as $item){
       if($wine->id==$item->customer_id){
           $empty_cart = false;
           return;
       }
     }
      var_dump($empty_cart);
  ?>

CodePudding user response:

The error is actually in your hasMany relationship, since user_id does not exist in the items migration.

You need to define the foreign key here (as you did in the Item model) since it appears most likely to be customer_id instead.

The error triggers from your blade code here: session('user')->items; -- as soon as items is accessed.

  • Related