代码之家  ›  专栏  ›  技术社区  ›  psudo

将数据合并到一个变量laravel-php-laravel中

  •  0
  • psudo  · 技术社区  · 5 年前

    我有三个模型: Country.php , Category.php Region.php 。所有这些模型都包含一个名为的公共字段 title 在数据库中。

    我想提取 标题 从每个模型中提取字段,并创建一个数组变量,以便我可以在其中运行它 foreach 在我看来,循环。

    这样做的最佳方法是什么?

    0 回复  |  直到 5 年前
        1
  •  0
  •   psudo    5 年前

    去了 union 查询:

            $opt1 = DB::table('countries')
            ->select('countries.name');
    
            $opt2 = DB::table('tourcategories')
            ->select('tourcategories.name');
    
            $opt3 = DB::table('regions')
            ->select('regions.name')
            ->union($opt1)
            ->union($opt2)
            ->get();
    
            dd($opt3);

    如果有人有其他最佳方法,请随时发帖。

        2
  •  0
  •   Militaru    5 年前
    // assuming that you have related this models
    $counties = County::with(['category','region'])->get();
    
    // And in view
    @foreach($counties as $county)
        {{$county->title}}
        {{$county->category->title}}
        {{$county->region->title}}
    @endforeach