Laravel/Lumen - 定义与参数的关系
Laravel/Lumen - defining a relationship with parameters
考虑一个模型 Employee 和一个模型 Project
员工table有一个属性类型可以分配以下值“1” 、“2”、“3”等
项目有许多员工
public function programmers() {
return $this->hasMany( 'App\Employee' )
->where( 'type', '1' );
} // hasMany programmers
public function testers() {
return $this->hasMany( 'App\Employee' )
->where( 'type', '2' );
} // hasMany testers
public function managers() {
return $this->hasMany( 'App\Employee' )
->where( 'type', '3' );
} // hasMany managers
而不是这些关系,我只想有一个:
public function employees( $type_id ) {
return $this->hasMany( 'App\Employee' )
->where( 'type', $type_id );
} // hasMany employees
它会像这样工作:
$app->get( '/employee', function() {
$project = App\Employee::find( 1 );
return $project->employees( "1" );
} );
但是,我收到以下异常:
ErrorException in Response.php line 402:
Object of class Illuminate\Database\Eloquent\Relations\HasMany could not be converted to string
查看报错内容:
ErrorException in Response.php line 402:
Object of class Illuminate\Database\Eloquent\Relations\HasMany could not be converted to string
响应中出现错误 class。出现此错误的原因是因为您在路由定义中 returning relationship 而不是 response:
$app->get( '/employee', function() {
$project = App\Employee::find( 1 );
return $project->employees( "1" );
} );
关系对象无法转换为字符串,因此响应 class 不知道如何处理它。
如果您想在浏览器中检查关系查询的结果,您需要return一个valid response。
尝试将您的路线更改为如下所示:
$app->get( '/employee', function() {
$project = App\Employee::find( 1 );
return response()->json($project->employees( "1" )->get());
} );
这会将您的查询结果输出到 JSON。还要注意 get()
的使用。这确保关系查询实际执行。
考虑一个模型 Employee 和一个模型 Project
员工table有一个属性类型可以分配以下值“1” 、“2”、“3”等
项目有许多员工
public function programmers() {
return $this->hasMany( 'App\Employee' )
->where( 'type', '1' );
} // hasMany programmers
public function testers() {
return $this->hasMany( 'App\Employee' )
->where( 'type', '2' );
} // hasMany testers
public function managers() {
return $this->hasMany( 'App\Employee' )
->where( 'type', '3' );
} // hasMany managers
而不是这些关系,我只想有一个:
public function employees( $type_id ) {
return $this->hasMany( 'App\Employee' )
->where( 'type', $type_id );
} // hasMany employees
它会像这样工作:
$app->get( '/employee', function() {
$project = App\Employee::find( 1 );
return $project->employees( "1" );
} );
但是,我收到以下异常:
ErrorException in Response.php line 402:
Object of class Illuminate\Database\Eloquent\Relations\HasMany could not be converted to string
查看报错内容:
ErrorException in Response.php line 402: Object of class Illuminate\Database\Eloquent\Relations\HasMany could not be converted to string
响应中出现错误 class。出现此错误的原因是因为您在路由定义中 returning relationship 而不是 response:
$app->get( '/employee', function() {
$project = App\Employee::find( 1 );
return $project->employees( "1" );
} );
关系对象无法转换为字符串,因此响应 class 不知道如何处理它。
如果您想在浏览器中检查关系查询的结果,您需要return一个valid response。
尝试将您的路线更改为如下所示:
$app->get( '/employee', function() {
$project = App\Employee::find( 1 );
return response()->json($project->employees( "1" )->get());
} );
这会将您的查询结果输出到 JSON。还要注意 get()
的使用。这确保关系查询实际执行。