【问题标题】:Laravel get profile nameLaravel 获取个人资料名称
【发布时间】:2015-08-05 12:51:45
【问题描述】:

我是 laravel 新手,正在制作简单的 CMS。所以我有一个简单的问题:

点击头像时我不想 - 重定向到用户个人资料 (http://example.com/profiles/nickname/id) 在数据库中,它保存了:

如您所见,我有 author_id,现在我需要从 users 表中获取作者姓名:

然后生成url:http://example.com/profiles/Evaldas/2(Evaldas,因为author_idtopics table中就是2

我的路线文件:

Route::get('topic/{tname}/{tid}', 'viewTopic@showTopic');

我的viewTopic.php 控制器:

<?php 

namespace App\Http\Controllers;
use DB;
use View;

class viewTopic extends Controller 
{
    public function showTopic($tname, $tid)
    {
        return View::make('posts', [
            'topics'  => DB::table('topics')
                ->where('id', $tid)
                ->where('seo_title', $tname)
                ->first(),
            'posts'  => DB::table('posts')
                ->where('topic_id', $tid)
                ->select()
                ->get()
        ]);
    }
}

和布局:

@extends('layouts.main')
@section('content')
<div class="media">
  <div class="media-left">
    <a href="HERE MUST BE HREF TO PROFILE">
      <img class="media-object" src="http://localhost/uploads/avatars/2.jpg" style="width: 64px">
    </a>
  </div>
  <div class="media-body" rel="#author{{ $topics->author_id }}">
    <h4 class="media-heading">{{ $topics->title }}</h4>
    @if(!empty($topics->text))
    {{ $topics->text }}
    @else
    Message empty :(
    @endif
  </div>
    @foreach($posts as $post)
    <div class="media">
  <div class="media-left">
    <a href="HERE MUST BE HREF TO PROFILE">
      <img class="media-object" src="http://localhost/uploads/avatars/1.png" style="width: 64px">
    </a>
  </div>
  <div class="media-body" rel="#post{{ $post->pid }}">
  {{ $post->text }}
  </div>
</div>
@endforeach
</div>
@stop

提前非常感谢:)

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    如果要使用查询生成器,可以使用 join() 方法:

    DB::table('posts')
    ->where('topic_id', $tid)
    ->join('users', 'user.id', '=', 'posts.author_id')
    ->select()
    ->get()
    

    这样,用户信息将可用:

     $post->nickname
    

    然后,您可以使用 laravel 助手构建您的 URL,例如,如果您有配置文件路由:

    <a href="{{route('profile', ['nickname' => $post->nickname, 'id' => $post->author_id]);}}">
    

    另一种方法是为您的表创建模型并定义它们之间的关系。

    看到这个:http://laravel.com/docs/5.1/eloquent-relationships

    使用这个方法,你可以写$post-&gt;author-&gt;nickname之类的东西

    【讨论】:

    • SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous (SQL: select * from topics` 内部连接 ​​users on users.id = topics.author_id where id = 14)` 和 SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous
    • 也许你可以试试写关系代码? :(我是新手我不能:(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-05
    • 1970-01-01
    • 2022-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多