雄辩有很多关系问题

时间:2015-08-09 20:42:29

标签: laravel-5 eloquent relationships lumen

我正在使用Eloquent为数据库构建一个带有流明微框架的API。

当我使用此代码从群组中获取购物清单时,一切正常

$group =  Group::with(['shoppingLists' => function($query) {
        }])->get();

返回以下对象

{
        "id": "797799c2-6044-4a3a-a3a6-a71fbb17de68",
        "name": "'t snackske",
        "description": "best group ever",
        "user_id": "7e74223a-ea06-46bf-ab1a-abb01b287e32",
        "created_at": "2015-08-09 20:06:40",
        "updated_at": "2015-08-09 20:06:40",
        "shopping_lists": [
            {
                "id": "2423eb3c-7dab-4672-b382-895788dec6a0",
                "name": "shop",
                "description": "food",
                "user_id": "7e74223a-ea06-46bf-ab1a-abb01b287e32",
                "group_id": "797799c2-6044-4a3a-a3a6-a71fbb17de68",
                "created_at": "2015-08-09 20:06:40",
                "updated_at": "2015-08-09 20:06:40"
            }
        ]
}

当我检查记录的查询时,我得到以下查询:

{
    "query": "select * from `groups`",
    "bindings": [],
    "time": 0.31
},
{
    "query": "select * from `shopping_lists` where `shopping_lists`.`group_id` in (?)",
    "bindings": [
        "797799c2-6044-4a3a-a3a6-a71fbb17de68"
    ],
    "time": 0.34
}

但是当我尝试为购物清单选择特定字段时,此查询不会返回任何记录 查询构建器:

$group =  Group::with(['shoppingLists' => function($query) {
            $query->addSelect('id', 'name', 'description');
        }])->get();

回应:

{
        "id": "797799c2-6044-4a3a-a3a6-a71fbb17de68",
        "name": "Group",
        "description": "testgroup",
        "user_id": "7e74223a-ea06-46bf-ab1a-abb01b287e32",
        "created_at": "2015-08-09 20:06:40",
        "updated_at": "2015-08-09 20:06:40",
        "shopping_lists": []
}

来自getQueryLog函数的查询

{
    "query": "select * from `groups`",
    "bindings": [],
    "time": 0.23
},
{
    "query": "select `id`, `name`, `description` from `shopping_lists` where `shopping_lists`.`group_id` in (?)",
    "bindings": [
        "797799c2-6044-4a3a-a3a6-a71fbb17de68"
    ],
    "time": 0.32
}

当我从mysql的查询日志中复制并粘贴最后一个查询时,我得到了正确的行。出于某种原因,雄辩并没有显示来自shopping_lists的数据。

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Group extends Model
{
    protected $increments = false;

    protected $fillable = [
        'id',
        'name',
        'description',
        'user_id'
    ];

    protected $primaryKey = 'id';

    /**
     * Get shoppinglists from this group
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function shoppingLists()
    {
        return $this->hasMany('App\ShoppingList', 'group_id', 'id');
    }
}

1 个答案:

答案 0 :(得分:2)

您可能必须将外键列添加到Laravel的addSelect()方法才能实现它的魔力。

Group::with(['shoppingLists' => function($query) {
    $query->addSelect('id', 'group_id', 'name', 'description');
}])->get();