mercredi 4 décembre 2019

Laravel 5.7 john query with Null relatiion

I have a relation BookUser(one) to Book(many). one Book model, 'borrowing_user_id' (if null mean book is available).

I tried to set it as below query, but this query does not show the available books, only show that borrowing books.How can I set a john query for all book?

    $query = Book::select( 'books.*')
    ->john( 'bookUsers' , 'bookUsers.id' , '=', 'books.borrowing_user_id' );
    /**
    query result
    books.book_name | books.borrowing_user_id | bookUsers.name
    BookA           | 1                       | Tom
    BookC           | 5                       | Peter
    */

My want result just like as below

books.book_name | books.borrowing_user_id | bookUsers.name
BookA           | 1                       | Tom
BookB           | Null                    | Null
BookC           | 5                       | Peter

BookUser model

class BookUser extends Model 
{
    use SoftDeletes;

    protected $fillable = [
        'name'
        ,'created_at'
        ,'updated_at'
        ,'deleted_at'
    ];
}

public function books()
{
    return $this->hasMany(Book::class, 'borrowing_user_id', 'id');
}

Book model

class BookUser extends Model 
{
    use SoftDeletes;

    protected $fillable = [
        'borrowing_user_id'  //nullable
        ,'book_name'
        ,'created_at'
        ,'updated_at'
        ,'deleted_at'
    ];
}

public function borrowing_user()
{
    return $this->belongsTo(User::class, 'borrowing_user_id', 'id');
}


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire