Laravel / Lumen - 定义与参数的关系

时间:2016-06-29 21:58:52

标签: laravel orm lumen

考虑模型员工和模型项目

员工表具有属性类型,可以为其分配以下值“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

1 个答案:

答案 0 :(得分:2)

查看错误消息的内容:

  

Response.php第402行中的ErrorException:   类Illuminate \ Database \ Eloquent \ Relations \ HasMany的对象无法转换为字符串

Response类中发生错误。出现此错误的原因是您在路线定义中返回关系而不是响应

$app->get( '/employee', function() {
    $project = App\Employee::find( 1 );
    return $project->employees( "1" );
} );

关系对象无法转换为字符串,因此Response类不知道如何处理它。

如果您想在浏览器中查看关系查询的结果,则需要返回valid response

尝试将路线更改为以下内容:

$app->get( '/employee', function() {
    $project = App\Employee::find( 1 );
    return response()->json($project->employees( "1" )->get());
} );

这会将您的查询结果输出到JSON。另请注意get()的使用。这可以确保实际执行关系查询。

相关问题