dongshi1914 2016-01-28 06:55
浏览 27
已采纳

如何从博客Laravel 5.2获取用户名

I made a blog in Laravel 5.2. I'am having trouble displaying a username associated with that blog. My flyers are linked with a user_id, but I cant get the actual username of the flyer created.

Here is my User relation with Flyer:

/**
* One user can have many Travel Flyers.
*/
    public function travelFlyers() {
        return $this->hasMany(TravelFlyers::class);
    }

Here is my Flyer model associating a user:

/**
     * A Travel Flyer belongs to a user.
     */
    public function user() {
        return $this->belongsTo('App/User', 'user_id');
    }

Here is my show method for displaying flyers:

 /**
     * Show a Travel Flyer in detail.
     * -- with title being the url
     */
    public function show($title) {
        //
        $travelFlyer = TravelFlyers::TravelFlyerLocatedAt($title);

        // return a view with the travel Flyer.
        return view('travelflyers.show', compact('travelFlyer'));
    }

And here is my flyer_table:

public function up()
    {
        Schema::create('travel_flyers', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->string('title');
            $table->string('excerpt');
            $table->text('description');
            $table->string('country');
            $table->string('state');
            $table->string('city');
            $table->double('lat', 20, 10);
            $table->double('lng', 20, 10);
            $table->timestamps();
            $table->timestamp('published_at');
        });
    }

I need to do something like this:

        @foreach($travelFlyers as $flyer)
            <div class="col-md-12">
                <p><b>Username:</b> {{ $flyer->username }}</p>
            </div>
        @endforeach


        This works fine, but I need username, not ID

         @foreach($travelFlyers as $flyer)
            <div class="col-md-12">
                <p><b>Username:</b> {{ $flyer->user_id }}</p>
            </div>
        @endforeach
  • 写回答

1条回答 默认 最新

  • dongshan4316 2016-01-28 07:13
    关注
    {{ $flyer->username }}
    

    A flyer has no username, a user has a username. But what flyer has is a user, so you need to use

    {{ $flyer->user->username }}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧