我有两个表:
users
{ id, username }
items
{ id, user_id }
在 Laravel 中,我如何正确返回项目永久链接上的用户名?
例如:
item #39 by JohnSmith
我尝试了以下方法:
$items = DB::table('items')->where('id', '=', 39)->first();
$username DB::table('users')->where('id', '=', $items->user_id)->first();
item #{{ $items->id }} by {{ $username }}
最佳答案
在 models
目录中创建两个模型:
// User Model (app/models/User.php)
class User Extends Eloquent {
public function items()
{
return $this->hasMany('Item');
}
}
// Item Model (app/models/Item.php)
class Item Extends Eloquent {
public function user()
{
return $this->belongsTo('User');
}
}
现在您可以在 Controller 中使用如下内容:
$item = Item::with('user')->find(39);
$username = $item->user->username;
关于php - 从一张表返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22923603/