adr1enbe4udou1n / laravel-boilerplate

Laravel 5.7 Boilerplate based on Bootstrap 4 and Vue Tabler for Backend.
https://laravel-boilerplate.okami101.io
MIT License
259 stars 107 forks source link

Get Relation data in Search results #60

Closed webdesign7 closed 6 years ago

webdesign7 commented 6 years ago

Hi,

Sorry I am bit new to Laravel and here I am stuck. Will appreciate your help.

Basically I got Model called ProductCategory which can have subcategories. So in my model I have:

protected $with = [
        'media',
        'meta',
        'parent',
        'children',
    ];
public function parent()
    {
        return $this->belongsTo(self::class, 'parent_id');
    }

    public function children()
    {
        return $this->hasMany(self::class, 'parent_id');
    }

Now the problem is that in ProductCategoryController->Show(...) function I am getting the parent object but in ProductCategoryController->Search(..) I dont.

Please see attachements .. they will make more sense.

screen shot 2018-05-12 at 20 32 37 screen shot 2018-05-12 at 20 32 02

Do you have any ideas ? ... I spent a few hours and I couldnt figure out :(

Thanks Sergiu

adr1enbe4udou1n commented 6 years ago

Hello,

I'm pretty sure this because you use a query SQL join on search method, so "$with" property cant apply in this case. Just add manually a query join with his parent and it should work.

webdesign7 commented 6 years ago

Thanks @adr1enbe4udou1n

I thoight so but I tried to put this in search function:

_$query->leftJoin('product_categories', 'product_categories.id', '=', 'parentid');

but I got :

"SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'product_categories' (SQL: select count(*) as aggregate from product_categories left join product_categories on product_categories.id = parent_id)


/**
     * Show the application dashboard.
     *
     * @param Request $request
     *
     * @throws \Exception
     *
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator|\Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    public function search(Request $request)
    {

        /** @var Builder $query */
        $query = $this->productCategories->query();

        if (! Gate::check('view product_categories')) {
            // Filter to only current user's posts
            $query->whereUserId(auth()->id());
        }

        $query
            ->leftJoin('product_categories', 'product_categories.id', '=', 'parent_id');

        /** @var RequestSearchQuery $requestSearchQuery */
        $requestSearchQuery = new RequestSearchQuery($request, $query, [
            'name',
            'summary',
            'body',
        ]);

        if ($request->get('exportData')) {
            return $requestSearchQuery->export([
                'name',
                'status',
                'product_categories.created_at',
                'product_categories.updated_at',
            ],
                [
                    __('validation.attributes.title'),
                    __('validation.attributes.status'),
                    __('labels.created_at'),
                    __('labels.updated_at'),
                ],
                'product_categories');
        }

        return $requestSearchQuery->result([
            'product_categories.id',
            'product_categories.name',
            'product_categories.slug',
            'product_categories.status',
            'product_categories.created_at',
            'product_categories.updated_at',
        ]);

    }```
adr1enbe4udou1n commented 6 years ago

It's because you join with the same table with same alias. Try with a different alias : https://stackoverflow.com/questions/24570209/not-unique-table-alias-in-mysql?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa

webdesign7 commented 6 years ago

Getting there : I done this

$query ->leftJoin('product_categories as parent', 'parent.id', '=', 'product_categories.parent_id');

but in the response 'parent' value is still null

Do i need to modify search function somehow as I think it somehow needs to be included in response.

??

Thanks Serg

adr1enbe4udou1n commented 6 years ago

You must explicit the property of the parent you want get in the results. Example :

return $requestSearchQuery->result([
            'product_categories.id',
            'product_categories.name',
            'parent.name',
            'product_categories.slug',
            'product_categories.status',
            'product_categories.created_at',
            'product_categories.updated_at',
        ]);
webdesign7 commented 6 years ago

Perfect that worked.. 👍

But how come you could get 'owner' object in PostController->search() but in this case I have to be granular ?

Ideally I would like to get the whole object in the search result

Thanks Sergiu

adr1enbe4udou1n commented 6 years ago

Ha in fact i get this owner thanks to "$with" property.

For posts I use users join only for make order by working. So indeed strange it's not working on your side, maybe a particular case as it's the same table/object ?

adr1enbe4udou1n commented 6 years ago

Ha just re-looked quickly your code and finded why your parent was null, i didnt see it.

You're simply forget to add parent_id in your sql fields so we should have :

return $requestSearchQuery->result([
            'product_categories.id',
            'product_categories.name',
            'product_categories.parent_id',
            'product_categories.slug',
            'product_categories.status',
            'product_categories.created_at',
            'product_categories.updated_at',
        ]);

The related ids is mandatory for getting "with relation" working ;)

webdesign7 commented 6 years ago

Thanks , that worked perfect !!! :)

shirshak55 commented 6 years ago

@webdesign7 He used Eager loading. You can check in laravel docs also. You can also do it bro .And I guess you are duplicating lot of things why don't you abstract some of code to methods

Thanks

webdesign7 commented 6 years ago

@bloggervista for me personally wasn't too obvious the solution to that issue, being new to Laravel its normal I think for questions like that to come up.. especially on CMSes done by other developers.

shirshak55 commented 6 years ago

Don't worry keep learning :)