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

KingsleyO's avatar

Using relationship column in a query

I have my category list coming from this relationship

public $belongsToMany = [
        'catbuy' => [
        'Corymillz\Adverts\Models\Cat',
        'table' => 'corymillz_adverts_buyrequest_cat',
        'order' => 'cat_title',
        'key' => 'buy_id',
        'otherKey' => 'cat_id'
     
       ]
    ];

I created a simple filter using ajax to filter by up to 4 categories and location using the code below

function onFilterBuyRequest()
{

    $category = post('maincat', []);
    $location = post('location');
    $buy = Buy::get();
    $query = Buy::with('catbuy')->whereIn('cat_title', $category)->where('location', $location)->orderBy('created_at','desc')->get();
$requests = $query;
     return [
       ...
    ];
}

i keep getting the error

catbuy column does not exist

how to i write the query to get the data stored in catbuy to make up the filter query?

this works when storing data

$buy->catbuy = Input::get('...')
0 likes
8 replies
Sinnbeck's avatar

I am unsure why you have an array for a relationship. It is normally a method. Are you using a package for that to work?

Snapey's avatar

Are you sure this is Laravel code?

Snapey's avatar
$query = Buy::with('catbuy')->whereIn('catbuy', $category)

You are working with Buy model. Does Buy model have a catbuy column?

KingsleyO's avatar

Mistake, it is supposed to be cat_title and it is under catbuy which is actually the category relationship to the buy model

KingsleyO's avatar
KingsleyO
OP
Best Answer
Level 1

well resolved it looping through all categories and adding whereHas()


      $query = Buy::with('catbuy');

    foreach ($category as  $cat) {
    $query->whereHas('catbuy', function($q) use ($cat){
        $q->where('id', $cat);
    });
}

Snapey's avatar

sorry, not a good solution. What is your query count?

KingsleyO's avatar

I am using this if that is what you mean

$result = $query->orderBy('created_at','desc')->paginate(15);

Please or to participate in this conversation.