spotorm / spot2

Spot v2.x DataMapper built on top of Doctrine's Database Abstraction Layer
http://phpdatamapper.com
BSD 3-Clause "New" or "Revised" License
601 stars 101 forks source link

Is it possible to filter related entities with dynamic conditions? #247

Open nenadmilosavljevic opened 6 years ago

nenadmilosavljevic commented 6 years ago

Hello, I know that I can filter related entities using this:

public static function relations(MapperInterface $mapper, EntityInterface $entity)
{
    return [
        "english" => $mapper
                        ->hasMany($entity, "Message", "parent_id")
                        ->where(["language" => "en"]),
        "estonian" => $mapper
                        ->hasMany($entity, "Message", "parent_id")
                        ->where(["language" => "et")
    ];
}

Id' like to do something like ->where(["userId" => $userId) but userId is read dinamically each time.

FlipEverything commented 6 years ago

You can use php's $_SESSION variable for that.

->where(["language" => isset($_SESSION["user"]["language"]) ? $_SESSION["user"]["language"] : "en"])
vlucas commented 6 years ago

@nenadmilosavljevic You can add more query conditions on your relations dynamically when calling them too, i.e.:

$page->translations->where(['language' => $user->lang]);

You can then put this in to a helper function or something (anything you want really):

function getPageTranslationForUser(Page $page, User $user) {
    return $page->translations->where(['language' => $user->lang]);
}
nenadmilosavljevic commented 6 years ago

Does this mean that if I want to get all pages for specific language I have to querry db for each page? What is $page exactly?

vlucas commented 6 years ago

$page doesn't matter - it was just an example of getting page content specific to that user, so both the page and user are required. That can be literally any entity.