【问题标题】:Get filtered rows from a table and its pivot table using eloquent in laravel 5.6在 laravel 5.6 中使用 eloquent 从表及其数据透视表中获取过滤后的行
【发布时间】:2018-08-07 05:54:37
【问题描述】:

我有两个模型 Base_voter 和 Custom_list

Custom_list.php

public function base_voters()
{
    return $this->hasMany('App\Models\Base_voter', 'custom_pivot_base', 'custom_list_id', 'base_voter_id');
}

Base_voter

public function custom_lists()
{
    return $this->belongsToMany('App\Models\Custom_list', 'custom_pivot_base', 'custom_list_id', 'base_voter_id');
}

有一个包含两列的数据透视表 custom_pivot_base

custom_list_id, base_voter_id

现在,我需要检索其 customer_list_id = 1 和 street = $street,其中 city = $city 的 base_voter 列表。这些地址和城市列在 base_voters 表中。我如何在 laravel 中用 eloquent 做到这一点

【问题讨论】:

  • 这两个模型应该是belongsToMany 关系。

标签: php laravel eloquent


【解决方案1】:

Custom_list模型中改变你的关系

public function base_voters()
{
    return $this->belongsToMany('App\Models\Base_voter', 'custom_pivot_base', 'custom_list_id', 'base_voter_id');
}

同时改变你在Base_voter模型中的关系

public function custom_lists()
{
    return $this->belongsToMany('App\Models\Custom_list', 'custom_pivot_base', 'base_voter_id', 'custom_list_id');
}

您需要获取customer_list_id = 1base_voter 列表,这意味着通过id 1 获取customer_list,然后获取其相关的base_voters。像这样

$customList = Custom_list::with(['base_voters' => function($query) use ($city, $gender){  

                    $query->where('city',$city)->where('gender', $gender);

              }])->find(1);

现在你可以这样打印了

print_r($customList->base_voters);

【讨论】:

  • SQLSTATE[42S22]:未找到列:1054 'where 子句'中的未知列'base_voter.custom_pivot_base'(SQL:select * from base_voter where base_voter.custom_pivot_base 为空且base_voter.custom_pivot_base 不为空,base_voter.deleted_at 为空)
  • 你有custom_pivot_base 带有'custom_list_id' 和'base_voter_id` 字段的表吗?以及定义的关系?
  • 更新了答案,检查一下。你应该在两个模型中都有 belongsToMany
  • 好吧,它有效,现在我该如何制作性别 = $gender, city = $city 等过滤器
  • 这些字段在哪个表中?
【解决方案2】:

您正在寻找的是“hasManyThrough”关系。 https://laravel.com/docs/5.6/eloquent-relationships#has-many-through

请仔细阅读本文档并定义模型之间的关系。

【讨论】:

    猜你喜欢
    • 2017-10-17
    • 1970-01-01
    • 1970-01-01
    • 2020-11-09
    • 1970-01-01
    • 2019-09-29
    • 1970-01-01
    • 2021-01-09
    • 1970-01-01
    相关资源
    最近更新 更多