laravel与作者搜索

时间:2018-11-29 09:03:52

标签: php

与作者一起搜索以显示发布者和作者姓名的代码。

控制器

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>

1 个答案:

答案 0 :(得分:0)

欢迎来到stackOverflow!

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

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