Laravel Eloquentを使用して外部キーが所属しているユーザーの名前を取得します。Laravelを使用して外部キーに属するユーザーの名前を取得する方法は?
私はポストのモデルがあります:
Class Posts Extends Eloquent{
protected $table = 'posts';
protected $fillable = array('title, image, text, user_id');
public $timestamps = false;
}
と ユーザモデル:
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
私は閲覧するには、ユーザー名、タイトル、テキスト、画像の値をコントローラに送信したいが。 >記事は、その後、あなたはこれがポストテーブル上の任意のuser_id
探しますhasMany
public function posts(){
return $this->hasMany('App\Post');
}
を使用することができます -
public function index(){
// get all the bears
$posts = Posts::all();
return View::make('welcome', compact('posts'));
}
あなたは[関係](https://laravel.com/docs/5.5/eloquent-relationships) – aynber
を設定する必要があります@ aynber私はlaravelのドキュメントがあいまいなので、これのいくつかの例が好きです –