【发布时间】:2017-09-06 22:09:32
【问题描述】:
我正在尝试使用(并了解 Eloquent)从用户表中获取用户名,基于我存储在另一个表中的 user_id,但我尝试的一切似乎都遇到了障碍。 我尝试了一个循环(foreach),然后使用我认为 Eloquent 的正确语法来获得我需要的东西,但它不起作用。 我之前使用视图完成了此操作,它可以工作,但不能在控制器中工作。
希望这里有人可以根据我的代码向我展示这应该如何工作。
首席模特:
class Lead extends Model
{
protected $fillable = [
'bname', 'tname'
];
public function user()
{
return $this->belongsTo(User::class);
}
}
LeadController
class LeadController extends Controller
{
use Helpers;
public function index(Lead $leads)
{
$leads = $leads->get();
//foreach $leads, get the username from 'user_id' from user table
//return the leads, without the user_id, but with the username
return $leads;
}
}
User.php 中的函数(User 类扩展 Authenticatable)
public function leads()
{
return $this->hasMany(Lead::class);
}
潜在客户迁移
Schema::create('leads', function (Blueprint $table) {
$table->increments('lead_id')->nullable(false);
$table->string('bname')->nullable(false);
$table->string('tname')->nullable();
$table->integer('user_id')->index();
$table->timestamps();
});
希望这对你有意义,有人可以帮助我学习 :)
谢谢。
【问题讨论】:
标签: php mysql laravel-5 eloquent foreign-keys