Tomen
Tomen

Reputation: 4854

Lithium: Remove related documents in a remove-Filter of a model

I have a Games model which hasMany Avatars and Agents. When i remove the game, i want to clean up all the remaining data, so i also want to remove all Avatars and Agents with the corresponding game_id:

namespace app\models;

use app\models\Avatars;
use app\models\Agents;

class Games extends \lithium\data\Model
{
    public static function __init($options = array()) {
        parent::__init($options);
        $self = static::_instance(__CLASS__);

        Games::applyFilter('remove', function($self, $params, $chain) {

            $conditions = array( 'game_id' => $params['conditions']['_id'] );

            $message = new \app\extensions\helper\Message();
            $debugString = var_export($conditions, true);
            $message->addDebugMessage("params:{$debugString}");
            //Output: 
            //params:array ( 'game_id' => '4f301f69a170c8cf52000002', )


            if(!Agents::remove($conditions)) { $message->addErrorMessage('Es konnten nicht alle Agents geloescht werden.'); };
            if(!Avatars::remove($conditions)) { $message->addErrorMessage('Es konnten nicht alle Avatare geloescht werden.'); };

            return $chain->next($self, $params, $chain);
        });

    }
}

Though the game gets removed, agents and avatars remain in the MongoDB. Does someone have a hint on this?

Example of agent in db

>db.agents.find()
{ "_id" : ObjectId("4f301f71a170c8391f000000"), "game_id" : ObjectId("4f301f69a170c8cf52000002"), "type" : "army", "subtype" : "deer", "units" : 5, "xPos" : 5, "yPos" : 5 }

Upvotes: 0

Views: 385

Answers (1)

Nate Abele
Nate Abele

Reputation: 5770

I'd have to look, but I don't think remove() casts values. You'd need to do:

$conditions = array( 'game_id' => new MongoId($params['conditions']['_id']));

Upvotes: 3

Related Questions