Laravel 和 While 循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33419950/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel and a While Loop
提问by ngplayground
I'm new to Laravel and at the moment I have a piece of code in a Controller which without the while
loop it works, it retrieves my query from the database.
我是 Laravel 的新手,目前我在控制器中有一段代码,它在没有while
循环的情况下工作,它从数据库中检索我的查询。
public function dash($id, Request $request) {
$user = JWTAuth::parseToken()->authenticate();
$postdata = $request->except('token');
$q = DB::select('SELECT * FROM maps WHERE user_id = :id', ['id' => $id]);
if($q->num_rows > 0){
$check = true;
$maps = array();
while($row = mysqli_fetch_array($q)) {
$product = array(
'auth' => 1,
'id' => $row['id'],
'url' => $row['url'],
'locationData' => json_decode($row['locationData']),
'userData' => json_decode($row['userData']),
'visible' => $row['visible'],
'thedate' => $row['thedate']
);
array_push($maps, $product);
}
} else {
$check = false;
}
return response()->json($maps);
}
I am trying to loop through the returned data from $q
and use json_decode
on 2 key/val pairs but I can't even get this done right.
我正在尝试遍历从2 个键/值对返回的数据$q
并json_decode
在其上使用,但我什至无法正确完成此操作。
回答by Jeff Lambert
Don't use mysqli
to iterate over the results (Laravel doesn't use mysqli). Results coming back from Laravel's query builderare Traversable
, so you can simply use a foreach loop:
不要使用mysqli
迭代结果(Laravel 不使用 mysqli)。从 Laravel 的查询构建器返回的结果是Traversable
,因此您可以简单地使用 foreach 循环:
$q = DB::select('...');
foreach($q as $row) {
// ...
}
Each $row
is going to be an object and not an array:
每个$row
都将是一个对象而不是一个数组:
$product = array(
'auth' => 1,
'id' => $row->id,
'url' => $row->url,
'locationData' => json_decode($row->locationData),
'userData' => json_decode($row->userData),
'visible' => $row->visible,
'thedate' => $row->thedate
);
回答by erapert
- You're not using
$postdata
in that function so remove it. - Do not use mysqli in Laravel. Use models and/or the DB query functionality built in.
- You're passing the wrong thing to mysqli_fetch_array. It's always returning a non-false value and that's why the loop never ends.
- Why are you looping over the row data? Just return the query results-- they're already an array. If you want things like 'locationData' and 'userData' to be decoded JSON then use a model with methods to do this stuff for you. Remember, with MVC you should always put anything data related into models.
- 您没有
$postdata
在该功能中使用,因此将其删除。 - 不要在 Laravel 中使用 mysqli。使用内置的模型和/或数据库查询功能。
- 您将错误的内容传递给 mysqli_fetch_array。它总是返回一个非假值,这就是循环永不结束的原因。
- 为什么要遍历行数据?只需返回查询结果——它们已经是一个数组。如果您希望像 'locationData' 和 'userData' 这样的东西被解码为 JSON,那么使用带有方法的模型来为您做这些事情。请记住,对于 MVC,您应该始终将任何相关数据放入模型中。
So a better way to do this is with Laravel models and relationships:
因此,更好的方法是使用 Laravel模型和关系:
// put this with the rest of your models
// User.php
class User extends Model
{
function maps ()
{
return $this->hasMany ('App\Map');
}
}
// Maps.php
class Map extends Model
{
// you're not using this right now, but in case your view needs to get
// this stuff you can use these functions
function getLocationData ()
{
return json_decode ($this->locationData);
}
function getUserData ()
{
return json_decode ($this->userData);
}
}
// now in your controller:
public function dash ($id, Request $request) {
// $user should now be an instance of the User model
$user = JWTAuth::parseToken()->authenticate();
// don't use raw SQL if at all possible
//$q = DB::select('SELECT * FROM maps WHERE user_id = :id', ['id' => $id]);
// notice that User has a relationship to Maps defined!
// and it's a has-many relationship so maps() returns an array
// of Map models
$maps = $user->maps ();
return response()->json($maps);
}
回答by Ivan
You can loop over $q using a foreach
:
您可以使用 a 遍历 $q foreach
:
foreach ($q as $row) {
// Do work here
}
See the Laravel docs for more information.
有关更多信息,请参阅Laravel 文档。