我是Laravel的新手。如何在模型類的查詢範圍方法中返回數組對象
我使用laravel 5.4。
我想讓模型類中的查詢範圍方法返回一個數組對象。
但是,它似乎返回查詢生成器對象而不是數組對象。
如何在查詢範圍方法中返回數組而不是查詢構造器對象?
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Carbon\Carbon;
/**
* @method static VisitRecord create(array $attributes)
*/
class VisitRecord extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
public function scopeBounceZone($query) {
$collection = $query->get();
$bounceZoneList = [];
$collection->groupBy("bounce_zone")->each(function($group, $key) {
if ($group[0]["bounce_zone"] === 0) {
$bounceZoneList["goal"] = count($group);
}
if ($group[0]["bounce_zone"] === 1) {
$bounceZoneList["knock"] = count($group);
}
if ($group[0]["bounce_zone"] === 2) {
$bounceZoneList["approach"] = count($group);
}
if ($group[0]["bounce_zone"] === 3) {
$bounceZoneList["front"] = count($group);
}
if ($group[0]["bounce_zone"] === 4) {
$bounceZoneList["detail"] = count($group);
}
if ($group[0]["bounce_zone"] === 5) {
$bounceZoneList["closing"] = count($group);
}
if ($group[0]["bounce_zone"] === 6) {
$bounceZoneList["hook"] = count($group);
}
if ($group[0]["bounce_zone"] === 7) {
$bounceZoneList["finish"] = count($group);
}
});
return $bounceZoneList;
}
}
編輯
我不希望有上面的代碼在我的控制器類。我的控制器類變得很胖,所以我想將它移動到相關的模型類。任何方式來實現它?
EDIT2爲什麼它不將值添加到每個環的側上的陣列??
public function scopeBounceZone($query) {
$collection = $query->get();
$bounceZoneList = [];
$collection->groupBy("bounce_zone")->each(function($group, $key) {
echo "it's called ok";
// just a test.
$bounceZoneList[] = 1;
});
//array(0) { } array(0) { }
var_dump($bounceZoneList);
return collect($bounceZoneList);
}
}
EDIT 3
$集合= $查詢 - >的get(); ($ collection-> groupBy(「bounce_zone」) - > toArray());
array(12) {
[0]=>
array(13) {
["id"]=>
int(26)
["room_id"]=>
int(14)
["project_id"]=>
int(1)
["bounce_zone"]=>
int(0)
["bounce_reason"]=>
int(1)
["next_action"]=>
int(1)
["memo"]=>
string(0) ""
["staff_id"]=>
int(1)
["visited_at"]=>
string(19) "2017-05-15 00:00:00"
["weather"]=>
string(5) "snowy"
["created_at"]=>
string(19) "2017-05-15 15:02:35"
["updated_at"]=>
string(19) "2017-05-15 15:02:35"
["deleted_at"]=>
NULL
}
[1]=>
array(13) {
["id"]=>
int(51)
["room_id"]=>
int(10)
["project_id"]=>
int(1)
["bounce_zone"]=>
int(0)
["bounce_reason"]=>
int(0)
["next_action"]=>
int(2)
["memo"]=>
string(0) ""
["staff_id"]=>
int(1)
["visited_at"]=>
string(19) "2017-05-15 00:00:00"
["weather"]=>
string(5) "sunny"
["created_at"]=>
string(19) "2017-05-15 15:02:35"
["updated_at"]=>
string(19) "2017-05-15 15:02:35"
["deleted_at"]=>
NULL
}
and more!
}
你試過'返回$ bounceZoneList->指定者();'? –
爲什麼你想要返回一個數組而不是查詢來執行?查詢範圍是關於在執行之前修改查詢,而不是返回數據 –
@Antonis Tsimourtos不起作用。 – hytm