Laravel:如何在循环中显示其他表的值?

问题描述 投票:1回答:4

所以,我有这个代码打印用户启动的各种主题/线程。

它循环遍历Posts表,其中包含与帖子相关的数据。

在用户列中,它将显示user_id。但是我想访问User表并显示与user_name匹配的user_id列。这该怎么做?

<table border="2">
    <tr>
        <th>Topic</th>
        <th>User</th>
        <th>Replies</th>
        <th>Views</th>
        <th>Last Update</th>
    </tr>
    @foreach($topics as $topic)
        <tr>
            <td><a href="topics/{{$topic->id}}">{{$topic->topic_title}}</a></td>
            <td>{{$topic->id}}</td>
            <td>0</td>
            <td>0</td>
            <td>{{$topic->updated_at}}</td>
        </tr>
    @endforeach
</table>

控制器代码:

public function show($id)
    {
        $topics = Topic::where('board_id', $id)->get();
        return view('boards.show')->with('topics', $topics);
    }
php laravel laravel-5
4个回答
2
投票

在控制器eager load用户模型中:

$topics = Topic::where('board_id', $id)->with('user')->get();

在视图中:

<td>{{ $topic->user->user_name }}</td>

我假设您已经在user模型中定义了Topic关系:

public function user()
{
    return $this->belongsTo(User::class);
}

0
投票

你可以尝试这样的事情:

@foreach($topics as $topic)
    @php $user = DB::table('User')->where('id', $topic->id)->first(); @endphp;
    <tr>
        <td><a href="topics/{{$topic->id}}">{{$topic->topic_title}}</a></td>          
        <td>{{ $user }}</td>
        <td>0</td>
        <td>0</td>
        <td>{{$topic->updated_at}}</td>
    </tr>
@endforeach

0
投票

在你的Post模型中

public function user(){
     $this->belongsTo(User::class);
}

在您的刀片{{$ topic-> user-> name}}

<table border="2">
<tr>
    <th>Topic</th>
    <th>User</th>
    <th>Replies</th>
    <th>Views</th>
    <th>Last Update</th>
</tr>
@foreach($topics as $topic)
    <tr>
        <td><a href="topics/{{$topic->id}}">{{$topic->topic_title}}</a></td>
        <td>{{$topic->user->name}}</td>
        <td>0</td>
        <td>0</td>
        <td>{{$topic->updated_at}}</td>
    </tr>
@endforeach


0
投票

您需要首先在模型中定义关系,如下所示:

class User extends Model
{
    public function post()
    {
        return $this->hasMany("App\Post");
    }
}

class Post extends Model
{
    public function user()
    {
        return $this->belongsTo("App\User");
    }
}

然后在视图侧的循环中,您可以访问用户的数据,如下所示:

@foreach($topics as $topic)
    <tr>
        <td>{{$topic->user->name}}</td>

    </tr>
@endforeach

在这种情况下,您不需要使用“with”功能。你只需要获取主题,传递它们进行查看,迭代并获得用户的数据

© www.soinside.com 2019 - 2024. All rights reserved.