【问题标题】:Laravel/Lumen - defining a relationship with parametersLaravel/Lumen - 定义与参数的关系
【发布时间】:2016-11-01 19:41:34
【问题描述】:

考虑一个模型Employee和一个模型Project

employees 表 有一个属性type,可以分配以下值“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

【问题讨论】:

    标签: laravel orm lumen


    【解决方案1】:

    查看错误信息的内容:

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

    错误发生在 Response 类中。出现此错误的原因是您在路由定义中返回了relationship,而不是response

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

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

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

    试着把你的路线改成这样:

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

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

    【讨论】:

    • 感谢您的详细解释
    猜你喜欢
    • 2021-08-16
    • 2019-03-22
    • 2019-02-09
    • 1970-01-01
    • 2021-08-29
    • 2018-06-12
    • 1970-01-01
    • 2018-05-05
    相关资源
    最近更新 更多