簡體   English   中英

Laravel 5.1使用外鍵選擇項目帖子的用戶

[英]Laravel 5.1 Select user of a project post with a foreign key

我們正在為學校構建一個應用程序,用戶可以在其中上傳項目。 我有一個頁面,上面顯示了所有上傳的項目。 但我也想展示項目的上傳者。

我的項目模型:

class Project extends Model
{
   protected $fillable = [
   'title',
   'tags',
   'summary',
   'published_at'
 ];
}

我的用戶模型:

class User extends Model implements AuthenticatableContract,
                                AuthorizableContract,
                                CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;

/**
 * The database table used by the model.
 *
 * @var string
 */
protected $table = 'users';

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

/**
 * The attributes excluded from the model's JSON form.
 *
 * @var array
 */
protected $hidden = ['password', 'remember_token'];

public function Projects()
{
    return $this->hasMany('App\Project');
}
}

我的遷移create_projects_table

public function up()
{
    Schema::create('projects', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users');
        $table->string('title');
        $table->string('tags');
        $table->string('summary');
        $table->string('file_name');
        $table->timestamp('published_at');
        $table->timestamps(); 
        $table->softDeletes();
    });
}

我的看法以及如何顯示所有項目:

@foreach ($projects as $project)
<article>
    <h2><a href="projects/{{ $project->id }}">{{ $project->title }}</a></h2>
    <span>{{ $project->tags }}</span><br/>
    <img src="uploads/projects/{{ $project->file_name }}">
</article>
@endforeach

因此,在本文中,我想添加一些標題,例如“ Uploaded by:username”。 如何從用戶表中的項目表中選擇帶有外鍵的用戶名?

項目模型:

public function user()
{
    return $this->belongsTo('App\User');
}

$projects變量添加到您的視圖中,然后嘗試:

@foreach($projects as $project)
{
    <article>
        <h2><a href="projects/{{ $project->id }}">{{ $project->title }}</a></h2>
        <span>{{ $project->tags }}</span><br/>
        <img src="uploads/projects/{{ $project->file_name }}">
        <p>Uploaded by: {{ $project->user->name }}</p>
    </article>
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM