如何解决Laravel ORM查询具有两列和差异表的位置
我是Laravel新手,可能很傻
1.-查询两个表并在每个表中使用两列
class Post extends Model {
public function Comment()
{
return $this->hasMany('App\Comment');
}
}
找出Post模型的列type
。我想咨询type = 1
和title = foo
(评论模型)的位置。下面的示例仅包含标题。
$comments = Post::find(1)->comments()->where('title','=','foo')->first();
2。-我的第二个问题,有没有一种方法可以运行orm查询而不运行或呈现应用程序。我的意思是像sqlplus或mysql terminal。
解决方法
A1: Constraining Eager Loads问题1:我想咨询类型= 1和标题= foo(注释模型)的地方。
// 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:是否可以在不运行或呈现应用程序的情况下运行orm查询。
继续使用php artisan tinker
和上面文档的链接。
回答您的问题
// 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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。