antanas_sepikas
antanas_sepikas

Reputation: 5704

Symfony2 Doctrine Criteria

I have an Entity called "Machine" with an association to Entity "Event"

/**
 * @var ArrayCollection
 *
 * @ORM\OneToMany(targetEntity="Event", mappedBy="machine", fetch="EXTRA_LAZY", cascade={"persist", "remove"})
 */
private $events;

In my twig template I iterate over "Machine" entities

{% for machine in machines %}
    <tr>
        <td>{{ machine.name }}</td>
        <td>{{ machine.lastEvent.value }}</td>
    </tr>
{% endfor %}

I want to fetch last event for each machine

/**
 * Get machine current event value
 *
 * @return Event
 */
public function getLastEvent()
{
    $expression = Criteria::expr()
        ->eq('machine', $this->id);

    $criteria = Criteria::create()
        ->setMaxResults(1)
        ->where($expression)
        ->orderBy(['id' => 'DESC']);

    return $event = $this
        ->getEvents()
        ->matching($criteria)
        ->first();
}

When executing I get this error:

"Cannot match on ApiBundle\Entity\Event::machine with a non-object value. Matching objects by id is not compatible with matching on an in-memory collection, which compares objects by reference."

What I am doing wrong?

Upvotes: 3

Views: 3653

Answers (1)

Rapha&#235;l Mali&#233;
Rapha&#235;l Mali&#233;

Reputation: 4002

You have to replace

$expression = Criteria::expr()
        ->eq('machine', $this->id);

with

$expression = Criteria::expr()
        ->eq('machine', $this);

Because machine is a relation and Doctrine need to use the entity and not its ID.

Upvotes: 6

Related Questions