I'm having problems fetching data using Model::find()
with two conditions. I want to return one record that has the given member_id
AND its role
is guest
:
$member = CalendarMembers::find(["member_id" => $r->member_id, "role" => "guest"]);
But this isn't working. I have one user that when created, a new register is added to calendar_members
table specifying this user as parent
, yet, when attempting to fetch this user automatically created by just giving the member_id
, it will be fetched, which SHOULD NOT.
I cannot use other ways such as:
$member = \DB::table("calendar_members")->where([ ["member_id", "=", $r->member_id], ["role", "=", "guest"] ])->first();
Because then $member->delete()
or $member->destroy()
will throw an error saying either delete
or destroy
do not exist.
The find()
method uses ID to get a record. You need to use the where()
and first()
methods:
CalendarMembers::where(['member_id' => $r->member_id, 'role' => 'guest'])->first();
you should use where for multiple conditions and get the first row with first() method, find is basically an alias for wehre('id', $id)
To make it clear, find() method will perform database query and returns single model object as result. so find is equal to,
Model::where('id', 1)->first().
find()
returns Model object and where()
returns QueryBuilder. But you can directly perform on query Builder without fetching model, like,
Model::where('id', 1)->delete().