sunshine
sunshine

Reputation: 1963

How to write this query in Laravel 5.2?

I am using Laravel 5.2 ,how to write this query?

There are two tables,user and articles,they have a one-to-many relationship.

I want to query users according to these conditions:
1、Show users who have articles,not show users who have not articles.
2、Articles contain two types,published and not published, "1" indicates published,show published articles ,not show articles which not published.
3、30 users are shown per page.

Like this, it's not right ,how to modify it?

HomeController:

public function index()
{
    $users = User::with('articles')->where('is_published','=',1)->paginate(30);
    return view('index', compact('users'));
}

User:

class User extends Model implements AuthenticatableContract, CanResetPasswordContract, HasRoleAndPermissionContract

{
    use Authenticatable, CanResetPassword, HasRoleAndPermission;

    protected $fillable = [
        'name', 'email', 'password',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    public function articles()
    {
        return $this->hasMany(Article::class);
    }

}

Article:

class Article extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    //edit-1:         
    //Scope a query to only include status=1.
    public function scopeStatus($query)
    {
        return $query->where('status',1);
    }

}

edit:
@SSuhat @RamilAmr Thanks! If there is a Local Scope in Model "Article",how to modify the answer:

$query = User::with(['articles' => function ($q) {
                $q->where('is_published', 1);
            }])
         ->has('articles') //<<<<<<<<<
         ->paginate(30);
return $query;

Upvotes: 2

Views: 113

Answers (3)

oseintow
oseintow

Reputation: 7371

$query = User::with('articles')->wherehas('articles', function ($q) {
            $q->where('is_published', 1);
        })->paginate(30);
return $query;

I hope this helps you.

Upvotes: 0

Ramil Amerzyanov
Ramil Amerzyanov

Reputation: 1291

if the user has not any articles,the user will not be shown,how to filter?

Try this code:

$query = User::with(['articles' => function ($q) {
                $q->where('is_published', 1);
            }])
         ->has('articles') //<<<<<<<<<
         ->paginate(30);
return $query;

Upvotes: 1

ssuhat
ssuhat

Reputation: 7656

Try this:

$query = User::with(['articles' => function ($q) {
                $q->where('is_published', 1);
            }])->paginate(30);
return $query;

Upvotes: 3

Related Questions