我的数据库中有三个表。用户、雇主和工作。
一些用户是发布了一些工作的雇主。
我正在尝试按用户显示作业。我的代码:用户模型
public function jobs(){
return $this->hasManyThrough('App\Employer','App\Job');
}
路线:
Route::get('/find_user_jobs',function(){
$user=User::find(1);
foreach($user->jobs as $job){
echo $job->created_at."<br>";
}
});
但我得到这个错误
Column not found: 1054 Unknown column 'jobs.user_id' in 'field list' (SQL: select `employers`.*, `jobs`.`user_id` from `employers` inner join `jobs` on `jobs`.`id` = `employers`.`job_id` where `jobs`.`user_id` = 1)
我知道它试图在工作中找到 user_id 但这就是我想要它做的
我对程序的渴望 当我给用户 id 时,去雇主表搜索 user_id,如果它存在,去工作表并搜索雇主 ID 并返回所有具有雇主 ID 的工作。
用户迁移
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->integer('employer_id');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('users');
}
}
工作迁移
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateJobsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('jobs', function (Blueprint $table) {
$table->increments('id');
$table->integer('employer_id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('jobs');
}
}
雇主移民
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateEmployersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('employers', function (Blueprint $table) {
$table->increments('id');
$table->string('company_name');
$table->integer('user_id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('employers');
}
}