cloudcreativity / laravel-json-api

JSON API (jsonapi.org) package for Laravel applications.
http://laravel-json-api.readthedocs.io/en/latest/
Apache License 2.0
780 stars 109 forks source link

custom relationships #408

Closed ehsan5 closed 3 years ago

ehsan5 commented 5 years ago

hi I want to have this url api/v1/users/124/sender-transactions

and I definde custom relationship in App\User.php

 public function getSenderTransactions2Attribute()
    {
        $transactions = $this->transactions()->where("status",Enum::TRANSACTION_SUCCEED)->get();
        $this->senderRequests->each(function ($request) use (&$transactions) {
            if ($request->status == Request::STATUS_DONE || $request->status == Request::STATUS_COMPLETE) {
                $transaction = new Transaction();
                $transaction->price_daryafti = $request->finalPrice;
                $transaction->date = $request->miladiDate;
                $transaction->id = Enum::REQUEST."-".$request->name;
                $transaction->port = Enum::REQUEST;
                $transactions->push($transaction);

            }
        });
        return $transactions;
    }

and in users adapter :

protected function senderTransactions()
    {
        return $this->hasMany();
    }

Now I get this error "message": "JSON API relation HasMany cannot be used for an Eloquent Collection relation.",

I worked befor in previous version of your library Can you help me?

rekrios commented 5 years ago

Maybe after '->get()' you have ordinary collection, which isn't relationship at all. You should think how to return relationship

lindyhopchris commented 5 years ago

Hi! When you say it worked in a previous version, what version were you on and what version are you now on?

If you're able to return a query builder you'd need to use this: https://laravel-json-api.readthedocs.io/en/latest/basics/adapters/#queries-one-and-queries-many

If not, then what you're trying to do would need to be implemented using a completely custom relation. To do that write a class that:

  1. Extends CloudCreativity\LaravelJsonApi\Adapter\AbstractRelationshipAdapter
  2. Implements CloudCreativity\LaravelJsonApi\Contracts\Adapter\HasManyAdapterInterface.

Then put the logic in the methods there. Then in your users adapter:

protected function senderTransactions()
{
    return new MyCustomRelation();
}

That should get it working for now. Though think this highlights that I should add a relation that can handle a Collection... will add it to the to-do list, but I'm severely pushed for time at the mo because of a work deadline on 14 Sept.

lindyhopchris commented 3 years ago

Closing due to inactivity.