Get related entity before saving

Hi, I don't know how can I work with related entity before saving. I have 2 entites Document and DocumentType. When I can create new Document:

$document = new \Document();

and then set DocumentType fetched from database:

$document->setDocumentType(\DocumentType:findFirst(1));

and now I need to approach to DocumentType via getter in Document, but when the Document is not saved, getter returns null.

I suppose than magic getter does something like this:

$this->getRelated....

but I don't know how can I work with that. Please tell me how can do that. Thanks.



33.9k

Can you paste your models or db structure ?



1.5k
edited Feb '15
public function initialize()
{
    $this->hasOne("type", "DocumentType", "id", ['alias' => 'doctype');
}

$document->doctype = DocumentType::findFirst(1);

I have exactly the same issue.. When i want to validate that Document before saving, i want to check that DocumentType is set. The only way i found is to access $document->_related[type], but this is very ugly, as the validation will work only for newly created object, not the fetched ones.