【问题标题】:Laravel Get Username based on user_id from another tableLaravel 根据 user_id 从另一个表获取用户名
【发布时间】: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


    【解决方案1】:

    你可以使用

    $user = User::where('id', $userid)->first();

    在您的控制器中,假设您将用户 ID 存储在变量中,并且“id”是您在用户表中的列名。因此,您拥有用户模型,并且可以访问例如带有

    的用户名

    $name = $user->用户名

    【讨论】:

      猜你喜欢
      • 2018-06-30
      • 1970-01-01
      • 2017-08-14
      • 1970-01-01
      • 2017-03-21
      • 1970-01-01
      • 1970-01-01
      • 2018-07-09
      • 1970-01-01
      相关资源
      最近更新 更多