Search code examples
laraveleloquenteloquent-relationship

Laravel ORM query where with two columns and differents tables


I'm new in Laravel and maybe could be silly

1.- Query with two tables and using two columns in each table

class Post extends Model {

    public function Comment()
    {
        return $this->hasMany('App\Comment');
    }

}

Figure out the Post model has the column type. I want to consult where type = 1 and title = foo(comment model).The below example only has the title.

$comments = Post::find(1)->comments()->where('title', '=', 'foo')->first();

2.- My second question, Is there a way to run the orm queries without running or render the application. I mean like sqlplus or mysql terminal.


Solution

  • Q1: I want to consult where type = 1 and title = foo(comment model).

    A1: Constraining Eager Loads
    // From the docs 
    
    $users = App\User::with(['posts' => function ($query) {
        $query->where('title', 'like', '%first%');
    }])->get();
    
    
    
    // So in your case - 
    
    $comments = App\Comment::with(['posts' => function ($query) {
        $query->where('type', '=', 1); // Constraints on the Post model
    })->where('title', '=', 'foo')->first(); // Constraints on the Comment model
    

    Q2: Is there a way to run the orm queries without running or render the application.

    A2: - Use the Artisan Console

    Read up on using the php artisan tinker with the link to the docs above.