首页 > 解决方案 > 从两个不同表中的相同字段名称中获取数据并检测我们指的是哪个字段名称

问题描述

我已经为我的应用程序分配了搜索方法,并且我在两个表“users”表和“posts”表之间建立了关系,它们都有相同的字段名称“created_at”,当我想获取创建这篇文章时的数据时将在用户表 created_at 字段中而不是在帖子表 created_at 字段中带来日期。我想要的只是如何告诉系统我的意思是哪个表字段名称有所不同。

此日期来自 users 表中的 created_at 字段 此日期来自 users 表中的 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>


标签: phplaravellaravel-5.8

解决方案


你不恰当地称呼你们的关系。你不应该在那里使用连接。改用受约束的急切加载

日期不会有冲突,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);

推荐阅读