lunar icon indicating copy to clipboard operation
lunar copied to clipboard

ModelManifest Extending works but relationships are broken

Open RRosalia opened this issue 1 year ago • 1 comments

  • Lunar version: 1.0.0-beta.3
  • Laravel Version: 11.28.1
  • PHP Version: 8.3.12
  • Database Driver & Version: PDO (Mysql 8.4.2)

Expected Behaviour:

When i have a custom model e.g. App\Domain\Models\Cart i extend the original Lunar cart object.

<?php
namespace App\Domain\Models;

class Cart extends \Lunar\Models\Cart
{

}

Now lets say i have a $cart and i want to get the lines

$cart->load('lines');

I will get back an object with Lunar\Models\Cartline while i also have a App\Domain\Models\CartLine also extending its counterpart. Scherm­afbeelding 2024-10-18 om 19 25 11

After extensive debugging i have figured out the following. The addDirectory is what is causing the the method call to extending(BaseModel::class) is returning false for all the objects. If i comment this out it works as expected and returns me the App\Domain\Models\CartLine as expected.

<?php

namespace Lunar\Base;

class ModelManifest implements ModelManifestInterface
{
    /**
     * Add a directory of models.
     */
    public function addDirectory(string $dir): void
    {
        try {
            $modelClasses = Discover::in($dir)
                ->classes()
                // ->extending(BaseModel::class) If you remove this line it works as expected
                ->get();

            foreach ($modelClasses as $modelClass) {
                $interfaceClass = $this->guessContractClass($modelClass);
                $this->models[$interfaceClass] = $modelClass;
                $this->bindModel($interfaceClass, $modelClass);
            }
        } catch (DirectoryNotFoundException $e) {
            Log::error($e->getMessage());
        }
    }
}

I'm not 100% sure if this is intended behaviour because according to the docs there is a way to retrieve your model back: https://docs.lunarphp.io/core/extending/models.html#relationship-support

RRosalia avatar Oct 18 '24 17:10 RRosalia

When i add

ModelManifest::add(
            \Lunar\Models\Contracts\CartLine::class, App\Domain\Models\CartLine::class
        );

My relation also works but i cannot wrap my head around why this works like this.

RRosalia avatar Oct 18 '24 17:10 RRosalia

It works without that line as your models are not extending the BaseModel class directly, they will be extending CartLine or similar. ModelManifest::add(...) is the recommended approach.

alecritson avatar Apr 14 '25 10:04 alecritson