Home > OS >  can i get a value from the main table inside a function of a relation table? laravel with
can i get a value from the main table inside a function of a relation table? laravel with

Time:07-15

        $main->with(['relation' => function ($query) {
            $query->orderByRaw("main.colunm   relation.colunm DESC");
        }]);

something like this, where I would like to order by a value from the main table with one from the relation table

CodePudding user response:

You need to add join in order to get parent table columns.

$main->with(['relation' => function ($query) {
    $query->join('main', 'main.pk', '=', 'relation.fk')->orderByRaw("main.colunm   relation.colunm DESC");
}]);

It's also better to add aliases for table names so they don't conflict with relation columns.

Hopefully, This will work.

  • Related