【发布时间】:2020-05-01 10:38:33
【问题描述】:
我有一个与用户有关系的公司模型。我通过 php artisan make:migration:pivot companies users 使用 https://github.com/laracasts/Laravel-5-Generators-Extended 生成了一个名为 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');
【问题讨论】:
标签: laravel pivot-table has-many