首页 > 解决方案 > laravel 搜索作者

问题描述

与作者一起搜索以显示出版商和作者姓名的代码。

控制器

case "writer":
    $msgs = $this->communityModel->searchWriter($search); 
    // $boardCount = $community->searchWriterCount($search);
    break;

模型

public function searchWriter($search){
    return DB::table('users')
    ->select(['users.name','communities.num','communities.country','communities.title', 'communities.content','communities.hits','communities.commend','communities.created_at',])
    ->join('communities', 'communities.user_id', '=', 'users.id')
    ->where('users.name', 'like', '%' . $search . '%')
    ->get();
}

看法

@foreach($msgs as $msg)
    <tr>
        <td style="width:60px;">{{$msg->num}}</td>
        <td style="width:50px;"><img src="{{$msg->country}}" alt="국적"></td>
        <td style="overflow:hidden;white-space:nowrap;text-overflow:ellipsis;">
            <a href="{{route('community.show',['boardNum'=>$msg->num,'search'=>$search,'where'=>$where,'page'=>$page])}}">
                {{$msg->title}}
            </a>
        </td>

        @if($where == 'writer')
        <td style="width:150px;">{{$msg->name}}</td>
        @else
        <td style="width:150px;">{{$msg->user->name}}</td>
        @endif
        <td style="width:60px;">{{date('m-d',strtotime($msg->created_at))}}</td>
        <td class="text-right" style="width:70px;">{{$msg->hits}}</td>
        <td class="text-right" style="width:70px;">{{$msg->commend}}</td>
        <td class="text-right" style="width:150px;"></td>
    </tr>

这是一个错误问题。有解决办法吗?

<td style="width:150px;">{{$msg->user->name}}</td>

标签: php

解决方案


欢迎来到 stackOverflow!

您可以在使用它之前检查关系是否存在:

<td style="width:150px;">{{$msg->user?$msg->user->name:""}}</td>

推荐阅读