Please see my database query:
db.comments
.find({})
.forEach(function(doc) {
doc.comments.map(function(c) {
if (c.active == 1) {
c.status = 0;
}
});
db.comments.update(
{_id: doc._id},
{$set: {comments: doc.comments}});
});
I need to write with jenssegers/laravel-mongodb. please help me If anyone has an idea to solve this
class Comment extends Eloquent {}
$comments = Comment::all();
foreach ($comments as $c) {
$c->comments = array_map(function (&$com) {
if ($com->active == 1) $com->status = 0;
}, $c->comments);
$c->save();
}
Related
I use octobercms and User Extended plugin(Clacke). I try to render a pagination because for now i have a lot of registered users and they display on one page.
I use random users function from \classes\UserManager.php
public static function getRandomUserSet($limit = 7)
{
$returner = new Collection;
$userCount = User::all()->count();
if(!isset($userCount) || empty($userCount) || $userCount == 0)
return [];
if($userCount < $limit)
$limit = $userCount;
$users = User::all(); //paginate(5)
if(empty($users))
return $returner;
$users->random($limit);
$friends = FriendsManager::getAllFriends();
foreach($users as $user)
{
$userAdd = true;
if(!$friends->isEmpty())
{
foreach($friends as $friend)
{
if($user->id == $friend->id)
{
$userAdd = false;
break;
}
}
}
if($user->id == UserUtil::getLoggedInUser()->id)
$userAdd = false;
if($userAdd)
{
$returner->push($user);
}
}
return $returner->shuffle();
}
try to do this with changing return $returner->paginate(25); and $users = User::paginate(25); but throws me an error
An exception has been thrown during the rendering of a template
("Method paginate does not exist.").
After that i try to change directly in \components\User.php
public function randomUsers()
{
return UserManager::getRandomUserSet($this->property('maxItems'))->paginate(12);
}
But again the same error.
Tryed and with this code and render in default.htm {{ tests.render|raw }}
public function randomUsers()
{
$test = UserManager::getRandomUserSet($this->property('maxItems'));
return $test->paginate(10);
}
Again with no success. Could anyoune give me some navigation and help to fix this?
If you are using random users function from \classes\UserManager.php
I checked the code and found that its using Illuminate\Support\Collection Object. So, for that Collection Object pagination works differently
You need to use forPage method.
On the other hands paginate is method of Illuminate\Database\Eloquent\Collection <- so both collection are not same
Use forpage
// OLD return UserManager::getRandomUserSet($this->property('maxItems'))
// ->paginate(12);
TO
return UserManager::getRandomUserSet($this->property('maxItems'))
->forPage(1, 12);
forPage method works like forPage(<<PAGE_NO>>, <<NO_OF_ITEM_PER_PAGE>>);
so if you use forPage it will work fine.
if any doubt please comment.
I want to get all the user whose status is 0 and then update them to 1.
public function notification ()
{
$data = Ghar::where('status',0)->get();
foreach($data as $dat)
{
$id = $dat->id;
$aa['status'] = '1';
if(Ghar::find($id)->update($aa))
{
print_r('ok');
}
}
All these (same) answers can be narrowed down to:
$data = Ghar::whereStatus(0)->update(['status' => 1]);
Note: This doesn't trigger the update/save events as it is a mass update.
Try
public function notification ()
{
$data = Ghar::where('status',0)->get();
foreach($data as $dat)
{
$dat->status = 1;
$dat->save();
}
return
}
As you you have only getting data whose status is 0 and you want to set it to 1 which you can do simply by trying below code
public function notification ()
{
$data = Ghar::where('status',0)->get();
foreach($data as $dat)
{
// $dat is already a object of Ghar model so you don't need call find here you can simply do this
$dat->update(['status' => 1]);
}
}
Thanks
I have 3 models: Account - Partner - User, with the 3 in belongsToMany relations (account_user, account_partner). I would like to filter all the User partners, authorized by the User accounts.
I have wrote the basic foreach loop hell, and I would like to ask for some tips for optimizing this filtering (like evading n+1 and other problems).
$userPartners = [];
foreach (auth()->user()->accounts as $account) {
foreach ($account->partners as $partner) {
$inList = false;
foreach ($userPartners as $userPartner) {
if ($userPartner->id === $partner->id) {
$inList = true;
}
}
if (!$inList) {
$userPartners[] = $partner;
}
}
}
dd($userPartners);
Start by eager loading your relationships with load. This will avoid the N+1 problem:
$user = auth()->user()->load('accounts');
$userPartners = [];
$user->accounts->each(function ($account) use ($userPartners) {
$ids = $account->partners->pluck('id');
if (!in_array($account->id, $ids)) {
$userPartners[] = $account->partners->where('id', $account->id);
}
});
You can do something like this:
Controller.php
$userPartners = collect();
auth()->user()->accounts->each(function($account) use ($userPartners) {
$account->partners->each(function($partner) use ($userPartners) {
if(!$userPartners->contains('id', $partner->id)) $userPartners->push($partner);
});
});
dd($userPartners);
This is my Controller code:
$sql = "SELECT *,earth_distance(ll_to_earth(team.lat, team.lng), ll_to_earth(23.1215939329,113.3096030895)) AS distance FROM team where earth_box(ll_to_earth(23.1215939329,113.3096030895),1000) #> ll_to_earth(team.lat, team.lng); ";
$result = DB::select( \DB::raw( $sql ) );
How can I add pagination to this code to build my restful api?
iOS or android will send the "next page" parameter, how to use it and find the next section data?
As far as I know you can't paginate raw query, here's why:
$result = DB::select($sql);
$result here will have the array type and paginate() is the method from the Illuminate\Database\Query\Builder class.
Your case can be performed this way:
$items = DB::table('team')
->selectRaw('SELECT *,earth_distance(ll_to_earth(team.lat, team.lng), ll_to_earth(23.1215939329,113.3096030895)) AS distance')
->whereRaw('earth_box(ll_to_earth(23.1215939329,113.3096030895),1000) #> ll_to_earth(team.lat, team.lng)')
->paginate(10);
foreach($items as $item) {
echo $item->distance;
}
As you can see minimal effort is needed here to separate raw query to selectRaw() and whereRaw() methods.
Another option if you are trying to paginate dynamic columns that maybe you were processing calculations on for reporting is to create a sort method and pass in your array and params:
public function sort($array_of_objects, $sort_by=null, $order, $page)
{
$collection = collect($array_of_objects);
if ($sort_by)
{
if ($order=='desc') {
$sorted = $collection->sortBy(function($role) use ($sort_by)
{
return $role->{$sort_by};
})->reverse();
} else if ($order=='asc') {
$sorted = $collection->sortBy(function($role) use ($sort_by)
{
return $role->{$sort_by};
});
}
} else {
$sorted = $collection;
}
$num_per_page = 20;
if (!$page) {
$page = 1;
}
$offset = ( $page - 1) * $num_per_page;
$sorted = $sorted->splice($offset, $num_per_page);
return new Paginator($sorted, count($array_of_objects), $num_per_page, $page);
}
this is my first question here and i hope you can help me ..
I am trying to find a soloution of the towers of hanoi problem by three search ways (BFS-DFS-IDS) so I use "state" class whitch defined by 5 variables as here :
class state {
var $tower1 = array();
var $tower2 = array();
var $tower3 = array();
var $depth;
var $neighbors = array();
and it also has many function one of them is getneighbors() which supposed to fill the array $neighbors with state neighbors and they are from the type "state"
and here is the function :
function getneighbors ()
{
$temp=$this->copy();
$neighbor1= $this->copy();
$neighbor2= $this->copy();
$neighbor3= $this->copy();
$neighbor4= $this->copy();
$neighbor5= $this->copy();
$neighbor6= $this->copy();
if(!Empty($temp->tower1))
{
if(!Empty($neighbor1->tower2))
{
if(end($neighbor1->tower1) < end($neighbor1->tower2))
{
array_unshift($neighbor1->tower2,array_pop($neighbor1->tower1));
array_push($neighbors,$neighbor1);
}}
else
{
array_unshift($neighbor1->tower2, array_pop($neighbor1->tower1));
array_push($neighbors,$neighbor1);
}
if(!Empty($neighbor2->tower3))
{
if(end($neighbor2->tower1) < end($neighbor2->tower3))
{ array_unshift($neighbor2->tower3, array_pop($neighbor2->tower1));
array_push($neighbors,$neighbor2);
}}
else
{
array_unshift($neighbor2->tower3,array_shift($neighbor2->tower1));
array_push($neighbors,$neighbor2);
}
}
if(!Empty($temp->tower2))
{
if(!Empty($neighbor3->tower1))
{
if(end($neighbor3->tower2) < end($neighbor3->tower1))
{ array_unshift($neighbor3->tower1,array_shift($neighbor3->tower2));
array_push($neighbors,$neighbor3);
}
}
else
{
array_unshift($neighbor3->tower1,array_shift($neighbor3->tower2));
array_push($neighbors,$neighbor3);
}
if(!Empty($neighbor4->tower3))
{
if(end($neighbor4->tower2) < end($neighbor4->tower3))
{ array_unshift($neighbor4->tower1,array_shift($neighbor4->tower2));
array_push($neighbors,$neighbor4);
}
}
else{
array_unshift($neighbor4->tower3,array_shift($neighbor4->tower2));
array_push($neighbors,$neighbor4);
}
}
if(!Empty($temp->tower3))
{
if(!Empty($neighbor5->tower1))
{
if(end($neighbor5->tower3) < end($neighbor5->tower1))
{array_unshift($neighbor5->tower1,array_shift($neighbor5->tower3));
array_push($neighbors,$neighbor5);
}
}
else{
array_unshift($neighbor5->tower1,array_shift($neighbor5->tower3));
array_push($neighbors,$neighbor5);}
if(!Empty($neighbor6->tower2))
{
if(end($neighbor6->tower3) < end($neighbor6->tower2))
{ array_unshift($neighbor6->tower2,array_shift($neighbor6->tower3));
array_push($neighbors,$neighbor6);
}}
else{
array_unshift($neighbor6->tower2,array_shift($neighbor6->tower3));
array_push($neighbors,$neighbor6);}
}
return $neighbors;
}
note that toString and equals and copy are defined too
now the problem is that when I call getneighbors() it returns an empty $neighbors array
can you pleas tell me the problem ?
You have a scoping issue. $neighbors is a class variable and not a PHP global. Everywhere you refer to $neighbors change it to $this->neighbors.