【问题标题】:Laravel Relationships - access input from other tableLaravel 关系 - 从其他表访问输入
【发布时间】:2016-08-29 00:41:14
【问题描述】:

我无法正常工作。这应该很容易,但我不知道如何使用关系从不同的表访问用户玩家标签。

这是我的 User.php 模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'gamertag', 'slug', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
    ];


    // A user has many messages (Chat)
    public function chat () {
        return $this->hasMany('App\Chat');
    }
}

这是我的 Chat.php 模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Chat extends Model {


    protected $table = "chat";


    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'message', 'user_id'
    ];


    // A Chat (or message) belong to a user
    public function user() {
        return $this->belongsTo('App\User');
    }


}

这就是我检索消息的方式:

class HomeController extends Controller {


    public function index () {

        $messages = Chat::orderBy('created_at', 'desc')->get();

        return view('layouts.index', compact('messages'));
    }

}

为什么我无法显示玩家标签?

@foreach($messages as $message)
     <a class="author">{{ $message->user->gamertag }}</a>
@endforeach

/***** 编辑***/

这行得通:

{{ dd($message->user->gamertag) }}




// This does NOT
{{ $message->user->gamertag }}

【问题讨论】:

  • $message->user 的输出是什么?
  • 这太诡异了哈哈~
  • 明天早上我会试着弄清楚
  • @David 你能告诉我你的数据库架构,或者聊天和用户表吗?
  • 它可能工作正常,并且您有 另一个 变量导致错误。尝试 {{ @$messages->user->gamertag }} 看看错误是否仍然存在。如果是这样,那肯定不是那个引发异常的变量。

标签: php laravel eloquent relationship


【解决方案1】:

尝试使用急切加载:

$messages = Chat::orderBy('created_at', 'desc')->with('user')->get();

【讨论】:

  • 不,没什么。如果我死转储 {{ $message->user->gamertag }},我会得到玩家标签
  • 我不明白,你什么都得不到,还是你得到了游戏标签?如果你得到带有dd($message-&gt;user-&gt;gametag) 的游戏标签,这意味着它正在工作。
  • 这不可能是真的,如果 dd 有效,无论如何你应该会看到结果。也许您因为author 类而没有看到它?你能检查原始 HTML 输出吗?
【解决方案2】:

我想通了!一切都在这里工作,它只是在我的聊天表中,我插入了一条没有识别用户的消息,所以 user_id = 0,它正在抛出那个错误。愚蠢的错误。

【讨论】:

    猜你喜欢
    • 2019-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-17
    • 2021-03-26
    • 1970-01-01
    • 2018-04-15
    相关资源
    最近更新 更多