Laravel 4 eloquent models chaining additional wher

2019-02-27 16:37发布

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.

4条回答
Emotional °昔
2楼-- · 2019-02-27 16:50

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楼-- · 2019-02-27 16:50
$query = Member::where('user_id', 5);

if ( $someCondition )
{
    $query->where(....);
}

$members = $query->get();
查看更多
Rolldiameter
4楼-- · 2019-02-27 17:04

I don't believe Eloquent works like that.

Try this...

$members = new Member;
$members = $members->where('user_id', '=', 5);
$members = $members->get();
查看更多
Bombasti
5楼-- · 2019-02-27 17:07

Wouldn't you have to call find() instead of get() ?

查看更多
登录 后发表回答