rorecek / laravel-ulid

Laravel package for ULID (Universally Unique Lexicographically Sortable Identifier)
MIT License
52 stars 15 forks source link

Left join id is null when $incrementing = false #2

Closed paulm17 closed 2 years ago

paulm17 commented 6 years ago

Thanks for the library!

I have the following:

Tables:
CREATE TABLE font_awesome_categories (
    `id` binary(26) NOT NULL,
    `name` varchar(50) NOT NULL,
);

CREATE TABLE font_awesome_icons (
    `id` binary(26) NOT NULL,
    `type` varchar(10) NOT NULL,
    `prefix` varchar(3) NOT NULL,
    `icon` varchar(50) NOT NULL,
    `unicode` varchar(10) NOT NULL,
);

CREATE TABLE font_awesome_icon_categories (
    `id` binary(26) NOT NULL,
    `category_id` binary(26) NOT NULL,
    `icon_id` binary(26) NOT NULL,
);

SQL:
select fai.id, fac.category_id, type, prefix, icon, unicode 
from font_awesome_icons fai 
left join font_awesome_icon_categories fac on fac.icon_id = fai.id 
order by icon asc;

Model:
class FontAwesomeIcon extends Model
{
    public function categories()
    {
        return $this->hasManyThrough(            
            'App\Models\ContentEditor\FontAwesomeCategory', 
            'App\Models\ContentEditor\FontAwesomeIconCategory',
            'icon_id', // Foreign key on faIconCategory table...
            'id', // Foreign key on faCategory table...
            'id', // Local key on faIcon table...
            'category_id' // Local key on faIconCategory table...
        );
    }
}

Query:
$result = FontAwesomeIcon::leftJoin('font_awesome_icon_categories', 'font_awesome_icon_categories.icon_id', '=', 'font_awesome_icons.id')
    ->with('categories')
    ->orderBy('icon')
    ->get();

The id field is null:

attributes: array:11 [▼
    "id" => null
    "type" => "brands"
    "prefix" => "fab"
    "icon" => "500px"
    "unicode" => "f26e"
    "created_at" => null
    "updated_at" => null
    "deleted_at" => null
    "category_id" => null
]

Although I can resolve it for now, by adding a select to the query:

->select(
    'font_awesome_icons.id as id', 
    'font_awesome_icon_categories.category_id', 
    'font_awesome_icons.type',
    'font_awesome_icons.prefix',
    'font_awesome_icons.icon',
    'font_awesome_icons.unicode'
)