mardi 22 décembre 2015

Querying Relationships in Laravel 5.2

I am having issues trying to query an Eloquent relationship.

I have 2 tables

tbl_deals

  • id
  • deal_id
  • merchant_id

tbl_merchants

  • id
  • merchant_id
  • merchant_url_text

I defined a deal model as

class deal extends Model
{
//
    public function merchant() {
    return $this->hasOne('App\merchant', 'merchant_id', 'merchant_id');
    }
}

Now, I want to query all deals based where merchant_url_text = a variable in my controller

Here's what I am trying

$deals = deal::with('merchant')->get(); //Retrieving all the deals with merchants 

If I return $deals its giving me all deals with merchant relationship.

How do I constraint the deals by saying where merchant_url_text = $variable

I am trying

return $deals->where('merchant_url_text', $merchant_url_text)->get();

but it is giving me an error saying "Missing argument 1 for Illuminate\Support\Collection::get(), called in ..."

I tried to lookup the documentation for querying relationships in Laravel Docs. It talks about this example

$user = App\User::find(1);

$user->posts()->where('active', 1)->get();

In this case, its trying to get the first user and finding corresponding posts related to the user.

In my case I want to filter from all deals, the deals that have merchant_url_text = a specific variable in my controller.

Any help on how I can achieve this?

Thanks



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire