与多模型的laravel关系问题

时间:2017-12-27 20:36:52

标签: php laravel laravel-5 laravel-5.5

用户与creater一对一有关系,但creater与存档belongsToMany

有关系
$creatorQuery = User::query();
    $cultivator_id = 2;
    $creatorQuery = $creatorQuery->select('id', 'name', 'email', 'role');

    $creatorQuery = $creatorQuery->with('creater', function($q) {
        $q->whereHas('archive', function($q) use($cultivator_id) {
            $query->where('caltivater_id', $cultivator_id);
        });
    });

    $creators = $creatorQuery->get();

显示错误mb_strpos()要求参数1为字符串,给定对象

2 个答案:

答案 0 :(得分:0)

function应该传递到creater,因此您需要将调用更改为键/值数组:

$creatorQuery = $creatorQuery->with(['creater' => function($q) use($cultivator_id) {
    $q->whereHas('archive', function($q) use($cultivator_id) {
        $query->where('caltivater_id', $cultivator_id);
    });
}]);

答案 1 :(得分:0)

您已经说过要根据caltivater_id模型中定义的Archive值来获取用户。使用嵌套的whereHas()

$creators = User::whereHas('creator', function($q) use($cultivator_id) {
    $q->whereHas('archive', function($q) use($cultivator_id) {
        $q->where('caltivater_id', $cultivator_id);
    });
})
->with('creators')
->get();

或使用点符号:

$creators = User::whereHas('creator.archive', function($q) use($cultivator_id) {
    $q->where('caltivater_id', $cultivator_id);
})
->with('creators')
->get();