laravel - 如何获取每条评论的用户信息

时间:2018-06-01 11:08:42

标签: php laravel model

我有这些模特:

public static String hmacsha1(String url, String secretKey) throws
        UnsupportedEncodingException, NoSuchAlgorithmException,
        InvalidKeyException
{
    secretKey = secretKey.replace('-', '+');
    secretKey = secretKey.replace('_', '/');

    byte[] key = Base64.decode(secretKey, Base64.DEFAULT);

    SecretKeySpec sha1Key = new SecretKeySpec(key, "HmacSHA1");

    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(sha1Key);

    byte[] sigBytes = mac.doFinal(url.getBytes());

    String signature = Base64.encodeToString(sigBytes, Base64.DEFAULT);

    // convert the signature to 'web safe' base 64
    signature = signature.replace('+', '-');
    signature = signature.replace('/', '_');

    return signature;
}

我想要的是让每个评论的用户像class Post extends Model { protected $primaryKey = 'post_id'; public function comments() { return $this->hasMany(Comment::class, 'post_id', 'post_id'); } } class Comment extends Model { protected $primaryKey = 'comment_id'; public function post() { return $this->belongsTo(Post::class, 'post_id'); } } class User extends Authenticatable { protected $primaryKey = 'user_id'; public function comments() { return $this->hasMany(Comment::class, 'user_id', 'commenter_id'); } } class MyController extends Controller { public function post($id = null) { $post = Post::where('post_id', $id)->first(); $comments = $post->comments; } } 一样,以便轻松获得用户信息,如下所示:

$post->comments->user

我该怎么做?我想我需要一些名为@foreach($post->comments as $comment) {{ $comment->user->first_name.' '.$comment->user->last_name }} @endforeach 的东西,但它太复杂而且我感到困惑:|

2 个答案:

答案 0 :(得分:0)

是的,您可以使用

获取带有评论对象的用户对象
$post = Post::with('comments.user')->where('post_id', $id)->first();

并在评论模型中定义用户的映射

class Comment extends Model
{
    protected $primaryKey = 'comment_id';

    public function post()
    {
        return $this->belongsTo(Post::class, 'post_id');
    }

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

答案 1 :(得分:0)

只需在评论模型中创建函数,该函数必须返回此类关系

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

然后在评论对象上调用此函数