Question

I have two tables books and users . How I can get the users have books its id smaller than 6 using Laravel Eloquent?

Was it helpful?

Solution 2

You would need to post some more info about your intended schema along with your models (i.e. Book.php and User.php)

Looking at your schema it looks as though your Book model has a has many relationship with users. Where you say, "I want books to be related to users where books.id not exceed 5." If I understand what you are saying, you can use Book::where('id', '<=', 5)->get(). That will give you all of the books with ids [1,2,3,4,5].

I recommend reading the Eloquent docs here: Laravel Eloquent Docs

Here are some quick snippets I threw together that may help get you started with your Eloquent models.

/**
 * Define Models
 */

// User.php
class User extends Eloquent { }

// Book.php
class Book extends Eloquent {

    # ...

    public function users()
    {
        return $this->hasMany('User');
    }

    #...

}


// routes.php
Route::get('test/{book_id}', function($book_id)
{
    $book  = Book::find($book_id);
    $users = $book->users;
    return compact('book', 'users');
})

Then you can navigate to '/test/3' and this will display (as JSON) the book as well as the book's users.

Either that or (and i would recommend this) just open up tinker php artisan tinker and play around with that a bit.

Like I said, you would need to provide some more info if you need help beyond that.

Hope that helps.

OTHER TIPS

Your database

books This table should have: (id , user_id, name)
users This table should have: (id , name)

Your User model should have:

class User extends Eloquent {

   public function books() {
      return $this->hasMany('Book', 'user_id');
   }

}

Your Book model should have:

class Book extends Eloquent {

   public function user() {
      return $this->belongsTo('User');
   }

Query

$user = User::find(1);
$book_count = $user->books()->count();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top