2017-05-16 8 views
1

laravelのクエリと少し混在しています。Laravelの外部キーを使用したクエリ

私は記事のリストを持っています。私はこの記事の著者からのデータを入手したいと思います。

関係モデル条

public function author() 
{ 
    return $this->belongsTo('App\Models\Author'); 
} 

関係モデル著者

public function articles() 
{ 
    return $this->hasMany('App\Models\Article'); 
} 

私はこの$author = Author::with('articles')->first();

この試してみてください。

$author = Author::whereHas('articles', function ($query){ 
     $query->where('id', '1'); 
    }); 

そして他の多くのテストをしかし、私はすべてを理解していない。

私のコントローラで私の方法:

protected function index() 
{ 


    $articles = Article::published()->paginate(8); 

    return view('pages.blog', [ 
     'articles' => $articles, 
    ]); 
} 

そして上記のすべて、どのように私は私のforeachの中で私の見解で正しい情報を表示していますか?

ありがとうございました!

答えて

0

問題を解決するには、以下の方法で関係を定義する必要があります。

条クラスには、次のテーブル構造に基づいて、定義:

articles { 
    id : integer [primary key], 
    ..., 
    author_id : integer [foreign key] 
} 
class Article extends Illuminate\Database\Eloquent\Model { 

    protected $table = "articles";  

    // HERE YOUR CLASS CODE 

    public function author() { 
    return $this->belongsTo("Author", "author_id", "id"); 
    } 
} 

Authorクラスを以下のテーブル構造に基づいて、定義:

authors { 
    id : integer [primary key], 
    ... 
} 
class Author extends Illuminate\Database\Eloquent\Model { 

    protected $table = "authors";  

    // HERE YOUR CLASS CODE 

    public function articles() { 
    return $this->hasMany("Article", "author_id", "id"); 
    } 
} 

いつbelongsTohasManyの方法を使用すると、外部キーとローカルキーのラベルが適切であることがわかります。詳細については

@foreach ($articles as $article) 
    <p>Id {{ $article->id }}</p> 
    ... 
@endforeach 


https://laravel.com/docs/5.4/eloquent-relationships
https://laravel.com/docs/5.4/blade

あなたが例に従うことを持っているあなたのビューに情報を表示するには
関連する問題