php - 从两个不同表中的相同字段名称中获取数据并检测我们指的是哪个字段名称
问题描述
我已经为我的应用程序分配了搜索方法,并且我在两个表“users”表和“posts”表之间建立了关系,它们都有相同的字段名称“created_at”,当我想获取创建这篇文章时的数据时将在用户表 created_at 字段中而不是在帖子表 created_at 字段中带来日期。我想要的只是如何告诉系统我的意思是哪个表字段名称有所不同。
清单控制器.php
public function search(Request $request){
$posts = Post::with(['comments','category','creator'])
->join('users', 'posts.created_by', '=', 'users.id')
->where('slug', 'LIKE', '%'.$request->search. '%')
->orWhere('users.name', 'LIKE', '%'.$request->search. '%')
->where('status',1)->orderBy('posts.id','DESC')->paginate(5);
return view('front.listing',compact('posts'));
}
列表.blade.php
<div class="article_date">
by: <a href="{{ url('/author') }}/{{ $post->creator->id }}">{{ $post->creator->name }} </a> , {{$post->created_at->diffForHumans()}}
</div>
解决方案
你不恰当地称呼你们的关系。你不应该在那里使用连接。改用受约束的急切加载
日期不会有冲突,created_at
因为不会有加入。同时仍将您的搜索查询保持在关系的封闭范围内。
$posts = Post::with(['comments', 'category'])
->with(['creator' => function ($query) use ($request) {
$query->where('name', 'LIKE', '%' . $request->search . '%');
}])
->where('slug', 'LIKE', '%' . $request->search . '%')
->where('status', 1)
->orderBy('id', 'DESC')
->paginate(5);
推荐阅读
- reactjs - 错误:对象作为 React 子项无效(找到:[object Promise])。如果您打算渲染一组子项,请改用数组(React)
- python - 为什么没有解释和(真正)编译的语言?
- github - 我的 AWS CDK 管道中缺少 UpdatePipeline (SelfMutate) 阶段
- c# - 如何在 Blazor 服务器端使用模拟访问文件服务器上的文件夹
- javascript - 如何获取迭代 HTML 集合的特定 DOM 元素的路径?
- vue.js - vue,veeValidator,以编程方式验证字段
- assembly - 从 MSVC 表示法到 GCC 的汇编端口,用于读取 RIP
- laravel - 在 Laravel Blade 文件中使用 IF 条件的正确方法是什么?
- java - 如何在 Android 11 中将音频文件设置为铃声?
- amazon-web-services - 如何使用无服务器框架有条件地将 AWS Lambda 函数部署到 prd 阶段