我有一个与用户有联系的公司模型。我有一个通过https://github.com/laracasts/Laravel-5-Generators-Extended通过php artisan make:migration:pivot companies users
生成的名为game_user的数据透视表。我有以下迁移
public function up()
{
Schema::create('company_user', function (Blueprint $table) {
$table->unsignedBigInteger('company_id')->unsigned()->index();
$table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
$table->unsignedBigInteger('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->primary(['company_id', 'user_id']);
});
}
在我的公司模型中,我让员工担任该关系的职务
<?php
namespace App\Models;
use App\User;
use Illuminate\Database\Eloquent\Model;
class Company extends Model
{
public function employees()
{
return $this->hasMany(User::class);
}
}
在我的CompanyController上,我有以下内容
<?php
namespace App\Http\Controllers;
use App\Models\Company;
use Illuminate\Http\Request;
class CompanyController extends Controller
{
public function index($id)
{
return Company::find($id);
}
public function employees($id)
{
return Company::find($id)->employees;
}
}
但是当邮递员通过get请求来请求它时。
http://localhost/laravel_applications/myapi/public/api/company/1/employees
我收到500个内部服务器错误。 Laravel是否应该自动检测桌子?我非常确定它不会检测甚至找不到我的数据透视表。
这是我的路线,我通过以字符串形式返回来进行测试,效果很好。所以这条路在工作。
Route::get('company/{id}/employees', 'CompanyController@employees');
方法hasMany
应该用于一对多关系。您需要为多对多关系调用belongsToMany
方法。