skip to Main Content

When I send a query with Postman, the response looks like this:

Error messages

I’m pulling data like this from my ‘series’ table:

{
"id": 9770,
"name": "Name of serie",
"type": null,
"release_date": "2021-09-30 00:00:00",
"year": 2021,
"genre": "4,600,2815",
}

I want to include the relevant data that I extracted from the ‘genres’ table using the values in the ‘genre’ column in the main data under the name ‘genres’ in the main data.

This is what my ‘Serie’ and ‘Genre’ model looks like:

class Serie extends Model
{
    protected $table = 'series';

    public function genres()
    {
        $genreIds = explode(',', $this->genre);
        return Genre::whereIn('id', $genreIds)->get();
    }
}

class Genre extends Model
{
    protected $table = 'genres';
}

And I use it in Controller like this:

$page = $request->input('page', 1);
$perPage = $request->input('perPage', 10);

$allSeries = Serie::with('genres')->paginate($perPage, ['*'], 'page', $page);

return response()->json($allSeries, 200, [], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

When I use the ‘genres’ function in the Serie model as follows, the query is successful, but the ‘genres’ data appears empty:

public function genres()
{
    $genreIds = explode(',', $this->genre);
    return $this->hasMany(Genre::class, 'id', 'genre')->whereIn('id', $genreIds);
}

I also tried using a method via query like below but it didn’t work:

$query = Serie::query();

$query->with([
    'genres' => function ($query) {
        // genres ilişkisi için özel sorgular yapabilirsiniz
        $genreIds = explode(',', $this->genre);
        $query->whereIn('id', $genreIds);
    },
]);

$allSeries = $query->paginate($perPage, ['*'], 'page', $page);

I do not have the opportunity to add a column to the data in the Genres table indicating which main data they belong to.
How can I do this in Laravel?

2

Answers


  1. with callback function is not working when you return json response

    you should build query like this:

    $query = Serie::query();
    
    $query->with(['genres']);
    
    $query->whereHas('genres',function($q) {
           $genreIds = explode(',', $this->genre);
           $q->whereIn('id',$genreIds);
    });
    
    $allSeries = $query->paginate($perPage, ['*'], 'page', $page);
    
    Login or Signup to reply.
  2. What you want to do is to append an attribute to the JSON array:

    class Serie extends Model
    {
        protected $table = 'series';
        protected $appends = ['genres'];
    
        public function getGenresAttribute()
        {
            $genreIds = explode(',', $this->genre);
            return Genre::whereIn('id', $genreIds)->get();
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search