NeDiaz
NeDiaz

Reputation: 369

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.

Upvotes: 0

Views: 192

Answers (2)

FullStackOfPancakes
FullStackOfPancakes

Reputation: 1381

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.

Upvotes: 2

Daniel Lara
Daniel Lara

Reputation: 36

Answering with your question

// Answer 1 
Post::with('comments')->where([ 
    ['type', 1], 
    ['comments.title', '=', 'foo'] 
])->get();

// Answer 2 
// you can use tinker: https://laravel.com/docs/7.x/artisan#tinker

Upvotes: 1

Related Questions