【问题标题】:Laravel 5 add results from query in a foreach to arrayLaravel 5将foreach中的查询结果添加到数组
【发布时间】:2016-02-04 07:31:24
【问题描述】:

我的 Laravel 5 应用程序有问题。 我的控制器方法包含一个 foreach,它应该迭代以前的 Eloquent-result-array(它被命名为 $zipcodes)。因此,每个邮政编码都用于填写一个查询,该结果返回一个 Article-object(名为 $article)。 每次迭代结束时,它都应该将文章结果添加到一个数组 ($articles) 中,该数组在我的方法结束时用于在我的页面上显示文章。 也许有更好的选择来执行文章查询,而不是每次迭代,但我不知道如何。

更新

这对我的问题有效,无需在 foreach 中执行查询:Laravel multiple where clauses in query from given array

我现在的代码是

// grabs all zipcodes matching the distance
$zipcodes = $this->getZipcodes($zipCoordinateId, $distance);

foreach ($zipcodes AS $key=>$val)
{
    $zipcodes[$key] = (array) $val;
}

$codes = array_column($zipcodes, 'zc_zip');

$articles = Article::whereIn('zipcode', $codes)->get();

return view('pages.intern.articles.index', compact('articles'));

更新结束

我的搜索控制器:

<?php

namespace App\Http\Controllers;

use App\Article;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;

class SearchController extends Controller
{
public function getSearch(Request $request)
{
    if(($request->has('zipcode'))) {
        $zipcode = $request->input('zipcode');
        $distance = $request->input('distance');

        $zipCoordinateId = $this->getZipCoordindateId($zipcode);
        $zipcodes = $this->getZipcodes($zipCoordinateId, $distance);

        $articles = array();

        foreach($zipcodes as $value) {
            //$zipcode = $zipcodes[0]->zc_zip; // this is working
            $zipcode = $value->zc_zip;

            $article = Article::where('zipcode', $zipcode)->get();


           // add the $article each iteration to $articles
        }

        return view('pages.articles', compact('articles'));
    } else {
        return redirect('/articles');
    }
}

public function getZipCoordindateId($value) {
    $result = DB::table('zip_coordinates')
            ->where('zc_zip', '=' , $value)
            ->orWhere('zc_location_name', 'LIKE', $value)
            ->pluck('zc_id');
    return $result;
}

public function getZipcodes($id, $distance) {

    $result = DB::select(
        DB::raw("
            SELECT dest.zc_zip,
                ACOS(
                    SIN(RADIANS(src.zc_lat)) * SIN(RADIANS(dest.zc_lat))
                    + COS(RADIANS(src.zc_lat)) * COS(RADIANS(dest.zc_lat))
                    * COS(RADIANS(src.zc_lon) - RADIANS(dest.zc_lon))
                ) * 6380 AS distance
            FROM zip_coordinates AS dest
            CROSS JOIN zip_coordinates AS src
            WHERE src.zc_id = :id
            HAVING distance < :distance
            ORDER BY distance"), array('id' => $id, 'distance' => $distance));

    return $result;
}
}

我的看法:

@extends('layouts.default')

@section('content')
    <h1>All Articles</h1>
<hr/>

<search>
    {!! Form::open(['url' => 'intern/search']) !!}
        {!! Form::text('zipcode', null, ['class' => 'form-control']) !!}
        {!! Form::select('distance', [
          '5' => '5 km',
          '10' => '10 km',
          '25' => '25 km',
          '50' => '50 km',
          ], null, ['class' => 'form-control']) !!}
        {!! Form::submit('Suchen', ['class' => 'btn btn-success']) !!}
    {!! Form::close() !!}
</search>


@foreach($articles as $article)
    <article>
        <h2>
            <a href="{{ url('/articles', $article->id) }}">{{ $article->name }}</a>
        </h2>

        <div>
            <label>Description:</label>
            <p>{{ $article->description }}</p>
        </div>
        <div>
            <label>ZIPCODE:</label>
            {{ $article->zipcode }}
        </div>
        <div>
            <label>Published:</label>
            {{ $article->published }}
        </div>
        <div>
            <label>Rank:</label>
            {{ $article->rank }}
        </div>
    </article>
    <hr/>
@endforeach
@stop

希望你能帮助我,提前谢谢你。 量子论者

编辑

当我使用时

foreach($zipcodes as $key => $value)
        {
            $articles[] = Article::where('zipcode', $value->zc_zip)->get();
        }
        print_r($articles);

在搜索中使用另一个邮政编码并更新我的文章的邮政编码时,它会打印(目前,我的数据库中有三篇文章,两篇文章都有第一个邮政编码,在我的新邮政编码搜索范围内):

Array
(
[0] => Illuminate\Database\Eloquent\Collection Object
    (
        [items:protected] => Array
            (
                [0] => App\Article Object
                    (
                        [fillable:protected] => Array
                            (
                                [0] => name
                                [1] => description
                                [2] => profile
                                [3] => driverlicense
                                [4] => zipcode
                                [5] => published
                                [6] => rank
                                [7] => contact
                                [8] => note
                                [9] => pictures
                                [10] => publisher
                            )

                        [connection:protected] => 
                        [table:protected] => 
                        [primaryKey:protected] => id
                        [perPage:protected] => 15
                        [incrementing] => 1
                        [timestamps] => 1
                        [attributes:protected] => Array
                            (
                                [id] => 5
                                [name] => Test1
                                [description] => Lorem ipsum dolor sit amet, consetetur 
                                [profile] => Lorem ipsum dolor sit amet, consetetur
                                [driverlicense] => yes
                                [published] => no
                                [rank] => 10
                                [contact] => 1
                                [pictures] => 
                                [zipcode] => 89429
                                [note] => 
                                [publisher] => 1
                                [created_at] => 2015-11-04 01:45:18
                                [updated_at] => 2015-11-04 10:07:24
                            )

                        [original:protected] => Array
                            (
                                [id] => 5
                                [name] => Test1
                                [description] => Lorem ipsum dolor sit amet, consetetur
                                [profile] => Lorem ipsum dolor sit amet, consetetur
                                [driverlicense] => yes
                                [published] => no
                                [rank] => 10
                                [contact] => 1
                                [pictures] => 
                                [zipcode] => 89429
                                [note] => 
                                [publisher] => 1
                                [created_at] => 2015-11-04 01:45:18
                                [updated_at] => 2015-11-04 10:07:24
                            )

                        [relations:protected] => Array
                            (
                            )

                        [hidden:protected] => Array
                            (
                            )

                        [visible:protected] => Array
                            (
                            )

                        [appends:protected] => Array
                            (
                            )

                        [guarded:protected] => Array
                            (
                                [0] => *
                            )

                        [dates:protected] => Array
                            (
                            )

                        [dateFormat:protected] => 
                        [casts:protected] => Array
                            (
                            )

                        [touches:protected] => Array
                            (
                            )

                        [observables:protected] => Array
                            (
                            )

                        [with:protected] => Array
                            (
                            )

                        [morphClass:protected] => 
                        [exists] => 1
                        [wasRecentlyCreated] => 
                    )

            )

    )

[1] => Illuminate\Database\Eloquent\Collection Object
    (
        [items:protected] => Array
            (
                [0] => App\Article Object
                    (
                        [fillable:protected] => Array
                            (
                                [0] => name
                                [1] => description
                                [2] => profile
                                [3] => driverlicense
                                [4] => zipcode
                                [5] => published
                                [6] => rank
                                [7] => contact
                                [8] => note
                                [9] => pictures
                                [10] => publisher
                            )

                        [connection:protected] => 
                        [table:protected] => 
                        [primaryKey:protected] => id
                        [perPage:protected] => 15
                        [incrementing] => 1
                        [timestamps] => 1
                        [attributes:protected] => Array
                            (
                                [id] => 6
                                [name] => Test2
                                [description] => Lorem ipsum dolor sit amet, consetetur 
                                [profile] => Lorem ipsum dolor sit amet
                                [driverlicense] => yes
                                [published] => no
                                [rank] => 3
                                [contact] => 1
                                [pictures] => 
                                [zipcode] => 89428
                                [note] => 
                                [publisher] => 1
                                [created_at] => 2015-11-04 01:45:38
                                [updated_at] => 2015-11-04 09:58:01
                            )

                        [original:protected] => Array
                            (
                                [id] => 6
                                [name] => Test2
                                [description] => Lorem ipsum dolor sit amet, consetetur 
                                [profile] => Lorem ipsum dolor sit amet
                                [driverlicense] => yes
                                [published] => no
                                [rank] => 3
                                [contact] => 1
                                [pictures] => 
                                [zipcode] => 89428
                                [note] => 
                                [publisher] => 1
                                [created_at] => 2015-11-04 01:45:38
                                [updated_at] => 2015-11-04 09:58:01
                            )

                        [relations:protected] => Array
                            (
                            )

                        [hidden:protected] => Array
                            (
                            )

                        [visible:protected] => Array
                            (
                            )

                        [appends:protected] => Array
                            (
                            )

                        [guarded:protected] => Array
                            (
                                [0] => *
                            )

                        [dates:protected] => Array
                            (
                            )

                        [dateFormat:protected] => 
                        [casts:protected] => Array
                            (
                            )

                        [touches:protected] => Array
                            (
                            )

                        [observables:protected] => Array
                            (
                            )

                        [with:protected] => Array
                            (
                            )

                        [morphClass:protected] => 
                        [exists] => 1
                        [wasRecentlyCreated] => 
                    )

            )

    )

[2] => Illuminate\Database\Eloquent\Collection Object
    (
        [items:protected] => Array
            (
            )

    )

)

编辑 2

我 print_r 来自 $articles = Article::all(); 的文章,它使用相同的返回视图('pages.articles', compact('articles'));并显示在同一网站上:

Illuminate\Database\Eloquent\Collection Object
(
[items:protected] => Array
    (
        [0] => App\Article Object
            (
                [fillable:protected] => Array
                    (
                        ...
                    )

                [connection:protected] => 
                [table:protected] => 
                [primaryKey:protected] => id
                [perPage:protected] => 15
                [incrementing] => 1
                [timestamps] => 1
                [attributes:protected] => Array
                    (
                        ...
                    )

                [original:protected] => Array
                    (
                        ...
                    )

                [relations:protected] => Array
                    (
                    )

                [hidden:protected] => Array
                    (
                    )

                [visible:protected] => Array
                    (
                    )

                [appends:protected] => Array
                    (
                    )

                [guarded:protected] => Array
                    (
                        [0] => *
                    )

                [dates:protected] => Array
                    (
                    )

                [dateFormat:protected] => 
                [casts:protected] => Array
                    (
                    )

                [touches:protected] => Array
                    (
                    )

                [observables:protected] => Array
                    (
                    )

                [with:protected] => Array
                    (
                    )

                [morphClass:protected] => 
                [exists] => 1
                [wasRecentlyCreated] => 
            )

        [1] => App\Article Object
            (
                [fillable:protected] => Array
                    (
                        ..
                    )

                [connection:protected] => 
                [table:protected] => 
                [primaryKey:protected] => id
                [perPage:protected] => 15
                [incrementing] => 1
                [timestamps] => 1
                [attributes:protected] => Array
                    (
                        ...
                    )

                [original:protected] => Array
                    (
                        ..
                    )

                [relations:protected] => Array
                    (
                    )

                [hidden:protected] => Array
                    (
                    )

                [visible:protected] => Array
                    (
                    )

                [appends:protected] => Array
                    (
                    )

                [guarded:protected] => Array
                    (
                        [0] => *
                    )

                [dates:protected] => Array
                    (
                    )

                [dateFormat:protected] => 
                [casts:protected] => Array
                    (
                    )

                [touches:protected] => Array
                    (
                    )

                [observables:protected] => Array
                    (
                    )

                [with:protected] => Array
                    (
                    )

                [morphClass:protected] => 
                [exists] => 1
                [wasRecentlyCreated] => 
            )

        [2] => App\Article Object
            (
                [fillable:protected] => Array
                    (
                        ..
                    )

                [connection:protected] => 
                [table:protected] => 
                [primaryKey:protected] => id
                [perPage:protected] => 15
                [incrementing] => 1
                [timestamps] => 1
                [attributes:protected] => Array
                    (..
                    )

                [original:protected] => Array
                    (
                        ..
                    )

                [relations:protected] => Array
                    (
                    )

                [hidden:protected] => Array
                    (
                    )

                [visible:protected] => Array
                    (
                    )

                [appends:protected] => Array
                    (
                    )

                [guarded:protected] => Array
                    (
                        [0] => *
                    )

                [dates:protected] => Array
                    (
                    )

                [dateFormat:protected] => 
                [casts:protected] => Array
                    (
                    )

                [touches:protected] => Array
                    (
                    )

                [observables:protected] => Array
                    (
                    )

                [with:protected] => Array
                    (
                    )

                [morphClass:protected] => 
                [exists] => 1
                [wasRecentlyCreated] => 
            )

    )

)

所以我的 print_r($articles) 的输出应该是这样的。

编辑 3

我目前的 foreach 是:

foreach($zipcodes as $key => $value)
        {
            //$code = $zipcodes[0]->zc_zip; // working, prints out one article
            //$article = Article::where('zipcode', $code)->get();
            $article = Article::where('zipcode', $value->zc_zip)->get();
            //print_r($article);
        }
        print_r($article);

【问题讨论】:

  • 你能 print_r($zipcodes) 吗?
  • 是的,它显示: Array ( [0] => stdClass Object ( [zc_zip] => 97204 [distance] => 3.9266259510316 ) [1] => stdClass Object ( [zc_zip] => 97218 [距离] => 4.3622922988114 ) [2] => stdClass Object ( [zc_zip] => 97236 [距离] => 4.5967044919437 ) ) 编辑:三个项目是正确的,它们的距离为 5。Sry
  • 如果可行,试试我的答案。

标签: php arrays laravel laravel-5 add


【解决方案1】:

你可以试试这个:

foreach($zipcodes as $key => $value)
{
    $articles[] = Article::where('zipcode', $value->zc_zip)->get();
}
return view('pages.articles', compact('articles'));

查看:

@foreach($articles as $article)
<article>
    <h2>
        <a href="{!! url('/articles', $article->id) !!}">{!! $article->name !!}</a>
    </h2>

    <div>
        <label>Description:</label>
        <p>{!! $article->description !!}</p>
    </div>
    <div>
        <label>ZIPCODE:</label>
        {!! $article->zipcode !!}
    </div>
    <div>
        <label>Published:</label>
        {!! $article->published !!}
    </div>
    <div>
        <label>Rank:</label>
        {!! $article->rank !!}
    </div>
</article>
<hr/>
@endforeach

【讨论】:

  • 我说得对吗,像 $articles (对于我的契约)这样的东西不见了?不,不工作。
  • 你能再 print_r($value) 吗?
  • stdClass 对象 ( [zc_zip] => 97204 [distance] => 3.9266259510316 ) stdClass 对象 ( [zc_zip] => 97218 [distance] => 4.3622922988114 ) stdClass 对象 ( [zc_zip] => 97236 [距离] => 4.5967044919437)
  • 试试我的答案。我认为你的契约是错误的。所以我修改了它。
  • 对不起,忘了谈我的看法。它应该显示数据库中的所有文章。所以它有一个 @foreach($articles as $article) ... @endforeach
【解决方案2】:

你已经声明了 $articles = array();然后你将 $article (没有 s) 传递给紧凑函数,这就是为什么你会在你的视图中得到一个未定义的变量,当你在 foreach 中循环时你必须这样做:

@foreach($articles as $article)
....
@endforeach

【讨论】:

  • 对不起,这是从编辑我的代码到aldrin27的解决方案。正如你所写,它就在那里。 :)
  • @quantatheist 您现在遇到什么错误?我仍然看到您在 getSearch 方法中有 $article 并且它必须是 $articles[] = Article::where('zipcode', $zipcode)-&gt;get(); 否则您将返回一个空数组。
  • 使用您的解决方案,我将获得“未定义属性:Illuminate\Database\Eloquent\Collection::$id”-ErrorException。
猜你喜欢
  • 2016-04-04
  • 2016-05-06
  • 2018-03-15
  • 2020-10-18
  • 1970-01-01
  • 2019-12-24
  • 2019-06-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多