Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

axeldimaria's avatar

Best way to queries Database when using two models

Hello guys,

I am trying to get data from one table as an array and use this array to get data from another table. I thought this could be best done with the Eloquent model relationships but I dont know how. So I tried combining the query builders and I got an error. This code is shown below:

public function upvotedStories(){
        $username = Auth::user()->username;
        $liked = WhoUpvoted::where('user', $username)->pluck('story_id');
        $stories = Story::whereIn('id', $liked)->get();
        var_dump($stories);
    }

It gives this error: Argument 1 passed to Illuminate\Database\Grammar::parameterize() must be of the type array, integer given, called in /Applications/XAMPP/xamppfiles/htdocs/storytime/vendor/laravel/framework/src/Illuminate/Database/Query/Grammars/Grammar.php on line 307 and defined

The two tables are whoUpvoted and stories. whoUpvoted has three fields: id, story_id and user. Below is the model for the whoUpvoted:

class WhoUpvoted extends Eloquent {
    protected $table = 'whoUpvoted';
    protected $guarded = array('id');
    protected $fillable = array('story_id','user');

    /*
    / Establishing a relationship with Stories table
    */
    public function story()
    {
        return $this->belongsTo('Story');
    }
}

And for Stories:

class Story extends Eloquent {
    protected $table = 'stories';
    protected $guarded = array('id');
    protected $fillable = array('story','title', 'upvotes', 'author');
    /*
     * WhoUpvoted relationship
    */
    public function whoUpvoted()
    {
        return $this->hasMany('WhoUpvoted','story_id');
    }
}

Is there a best way to solve this using Eloquent models? or What is wrong with the code I have to provoke such an error?

Thanks for your help in advance, Axel.

0 likes
4 replies
jakeryansmith's avatar

Change $stories = Story::whereIn('id', $liked)->get(); to $stories = Story::whereIn('id', [$liked])->get(); WhereIn needs an array, you are passing an integer. When you use "pluck" you are getting an integer. This will fix the error.

Now in order to utilize Eloquents relationships, use "with". $stories = Story::with('whoUpvoted')->get(); This will return all from Story along with all from WhoUpVoted.

1 like
axeldimaria's avatar
axeldimaria
OP
Best Answer
Level 1

Thanks @jakeryansmith, That worked. But the $liked array contains only one element meanwhile there are many rows which should also be part. Maybe I'm not suppose to use pluck. A better question is: How to get one column of a query result as an array?

jakeryansmith's avatar

To get one column as an array you can use "lists" WhoUpvoted::where('user', $username)->lists('story_id');

2 likes

Please or to participate in this conversation.