skip to Main Content

I have 2 tables :-

  1. users – id,name,email, mobile

  2. user_info – id,user_id, store_name, startup_date

  3. User Model

    class EloquentUser extends Model
    {
    protected $table = ‘users’;

     /**
      * The attributes that are mass assignable.
      *
      * @var array
      */
     protected $fillable = [
         'name',
          'email',
        'mobile'
     ];
    

    }

  4. User Info Model

    class UserInfo extends Model
    {
    use HasFactory, SoftDeletes;
    public $table = ‘user_info’;

    }

Below is relationship on above 2 tables :-

public function info() {
        return $this->hasOne(UserInfo::class,'user_id','id');
    }

I want to order on base of startup_date but it is giving error column not found. Below is the query :-

$reponse = EloquentUser::with('info')->has('info')->orderBy('info.startup_date')->get();

2

Answers


  1. This error is due to the fact that the column startup_date is not present in the user_info table.
    You need to ensure that the column name matches the actual column in the table.

    If the column name is different or has been changed, you should update your code accordingly. Assuming the correct column name is start_date in the user_info table, you can modify your query as follows:

    $response = EloquentUser::with('info')->has('info')->orderBy('info.start_date')->get();
    

    Update the column name to actual column in your user_info table.

    Login or Signup to reply.
  2. You must modify your query and define the inverse relationship in the UserInfo model. The ORM you provided will not give the expected result.
    Create inverse relationship

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class, 'id','user_id');
    }
    

    Change the query to

    UserInfo::with('user')->orderBy('startup_date')->get();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search