flat3 / lodata

The OData v4.01 Producer for Laravel
https://lodata.io/
MIT License
80 stars 27 forks source link

Individual `BelongsTo` relationship not properly resolved #839

Closed mgerzabek closed 2 months ago

mgerzabek commented 3 months ago

Hi @27pchrisl,

on finding an odata-ish solution for my $expand pivot problem I created a custom BelongsTo relation on my pivot model Contactable like

 #[LodataRelationship]
public function customer(): BelongsTo
{
    $instance = $this->newRelatedInstance(Customer::class);
    $relation = $this->newBelongsTo(
        $instance->newQuery(),
        $this,
        'contactable_id',
        $this->getKeyName(),
        'customer'
    );
    $relation->getQuery()
        ->join(
            'contactables',
            function(JoinClause $join) {
                $join->on('contactables.contactable_id', '=', 'customers.id')
                    ->whereRaw('`contactables`.`contactable_type` = "customer"');
            }
        );
    return $relation;
}

The $metadata entry for the pivot table looks like

<EntityType Name="Contactable">
  <Key>
    <PropertyRef Name="id"/>
  </Key>
  <Property Name="id" Type="Edm.Int64" Nullable="false">
    <Annotation Term="Org.OData.Core.V1.Computed" Bool="true"/>
  </Property>
  <Property Name="contact_id" Type="Edm.Int64" Nullable="false"/>
  <Property Name="contactable_id" Type="Edm.Int64" Nullable="false"/>
  <Property Name="contactable_type" Type="Edm.String" Nullable="false" DefaultValue="customer">
    <Annotation Term="Org.OData.Core.V1.ComputedDefaultValue" Bool="true"/>
  </Property>
  <NavigationProperty Name="contact" Type="io.pragmatiqu.Contact" Nullable="true"/>
  <NavigationProperty Name="customer" Type="io.pragmatiqu.Customer" Nullable="true">
    <ReferentialConstraint Property="contactable_id" ReferencedProperty="id"/>
  </NavigationProperty>
</EntityType>

To me it looks like the NavigationProperty for customer is listed correctly.

With that setup Tinkerwell is able to relate a given Contact to a related Customer via pivot Contactable

use App\Models\Contact;
use App\Models\Contactable;
use App\Models\Customer;

$contact = Contact::find(15);
$contactables = $contact->contactables;

$contactables->first()->customer;

But when I try to emit the odata request …/odata/Contacts(15)?expand=contactables($expand=customer) the customer property always stays null.

Is this a bug? Where can I trace down the $expand?