Laravel ORM 查询,其中包含两列和不同的表
Laravel ORM query where with two columns and differents tables
我是 Laravel 的新人,可能有点傻
1.- 使用两个 table 查询并在每个 table
中使用两列
class Post extends Model {
public function Comment()
{
return $this->hasMany('App\Comment');
}
}
找出 Post 模型有列 type
。我想咨询wheretype = 1
和title = foo
(评论模型)。下面的例子只有标题。
$comments = Post::find(1)->comments()->where('title', '=', 'foo')->first();
2.- 我的第二个问题,有没有办法 运行 orm 查询而不 运行 宁或呈现应用程序。我的意思是像 sqlplus 或 mysql 终端。
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
阅读上面的文档,了解如何使用 php artisan tinker
和 link。
回答你的问题
// 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
我是 Laravel 的新人,可能有点傻
1.- 使用两个 table 查询并在每个 table
中使用两列class Post extends Model {
public function Comment()
{
return $this->hasMany('App\Comment');
}
}
找出 Post 模型有列 type
。我想咨询wheretype = 1
和title = foo
(评论模型)。下面的例子只有标题。
$comments = Post::find(1)->comments()->where('title', '=', 'foo')->first();
2.- 我的第二个问题,有没有办法 运行 orm 查询而不 运行 宁或呈现应用程序。我的意思是像 sqlplus 或 mysql 终端。
A1: Constraining Eager LoadsQ1: I want to consult where type = 1 and title = foo(comment model).
// 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
A2: - Use the Artisan ConsoleQ2: Is there a way to run the orm queries without running or render the application.
阅读上面的文档,了解如何使用 php artisan tinker
和 link。
回答你的问题
// 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