问题
I Have the following code (member is just a standard Eloquent model)
$members = new Member;
$members->where('user_id', '=', 5);
$_members = $members->get();
The last query run produces "SELECT * from members
", so it seems to be ignoring my where clause, what am I doing wrong here?
By the way I know I could do $members = new Member::where(...)
etc... but I will be adding the where
clauses in a loop in order to create filtering on the results from the database.
UPDATE
The only way around this seems to be to add a where that will catch all on initialization such as:
$members = Member::where('member_id', '<>', 0);
$members->where('user_id', '=', 5);
$_members = $members->get();
But this seems quite a bit of a hack. I am not trying to do anything complicated so I cant be the only one who has had this problem?
FIXED MAYBE
For anyone who has stumbled here I have fixed this by using:
$members = Member::query();
$members->where('user_id', '=', 5);
$_members = $members->get();
Not sure if that is the correct way but it works for me and doesn't appear like a hack.
回答1:
I don't believe Eloquent works like that.
Try this...
$members = new Member;
$members = $members->where('user_id', '=', 5);
$members = $members->get();
回答2:
There is a much better way to achieve what you need here using query scopes. Here is what you need to do.
In your Member.php model do the following:
public function scopeMembers($query, $condition1, $condition2)
{
if ( ! empty($condition1))
{
$query = $query->where('column1', $condition1);
}
if ( ! empty($condition2))
{
// Use if ( ! empty($condition2[0]) { $query->whereIn('column2', $condition2); } if you are exploding the input in the controller.
$query = $query->where('column2', $condition2);
}
}
In your controller do this:
protected $member;
public function __construct(Member $member)
{
$this->member = $member;
}
public function getMembers()
{
$condition1 = Input::get('condition1');
$condition2 = Input::get('condition2');
$members = $this->member->members($condition1, $condition2)->paginate(10);
return View::make('members', compact('members'));
}
This is a very basic example that can be expanded upon depending on what you need. As you can see you can pass as many conditions as you require to the query scope.
回答3:
Wouldn't you have to call find() instead of get() ?
回答4:
$query = Member::where('user_id', 5);
if ( $someCondition )
{
$query->where(....);
}
$members = $query->get();
来源:https://stackoverflow.com/questions/21738380/laravel-4-eloquent-models-chaining-additional-where-clauses