Laravel 5.3+DataTables关联查询报错:未知列jadwals.users_id
Hey, let's work through this error you're hitting with Laravel 5.3 and DataTables! The core issue here is that your query is trying to join the jadwals and users tables using a column that doesn't exist in jadwals. Let's break down the fixes step by step:
1. Verify the actual foreign key column in jadwals
First, double-check what the foreign key column is named in your jadwals table. The error says jadwals.users_id doesn't exist—and it's super common for this column to actually be named user_id (singular, which follows Laravel's default foreign key convention for linking to users.id).
You can confirm this quickly using Artisan Tinker:
php artisan tinker
Then run this command to list all columns in the jadwals table:
Schema::getColumnListing('jadwals');
Look for the column that's supposed to link to the users table.
2. Correct your DataTables join query
If the column is indeed user_id, update your DataTables query to use the correct column name. For example, if your original code looked like this:
return Datatables::of(Jadwal::leftJoin('users', 'jadwals.users_id', '=', 'users.id') ->select('jadwals.*', 'users.name')) ->make(true);
Change it to:
return Datatables::of(Jadwal::leftJoin('users', 'jadwals.user_id', '=', 'users.id') ->select('jadwals.*', 'users.name')) ->make(true);
3. Fix Eloquent relationships (if you're using them)
If you've defined a relationship in your Jadwal model, make sure it references the correct foreign key. If your model had this incorrect code:
public function user() { return $this->belongsTo(User::class, 'users_id'); // Wrong column name }
Update it to use the correct column:
public function user() { return $this->belongsTo(User::class, 'user_id'); // Correct column name }
You can then clean up your DataTables code to use the relationship instead of a raw join:
return Datatables::of(Jadwal::with('user')) ->addColumn('user_name', function($jadwal) { return $jadwal->user->name; }) ->make(true);
4. Check for accidental spaces in your column reference
The error SQL shows jadwals . users_id (with spaces around the dot)—if you accidentally added spaces in your query string (like 'jadwals . users_id'), remove those spaces to make it 'jadwals.users_id' (only relevant if your column is actually named users_id).
内容的提问来源于stack exchange,提问作者AyamSayur

