モデルで自分のメソッドの名前をどうすべきかについて、私は混乱しています。私はLaravel Eloquentの文書でそれが複数であると仮定していることを知っていますが、場合によってはエラーが出ます。例えば、私は、このクエリがあります:Eloquent関係メソッドの命名規則
$posts = Post::with(['comments','user', 'tag'])->findOrFail($id);
をして、私はこのような結果を印刷:
echo "<h1>".$posts->title.'</h1>';
echo "<h2> created by: ".$posts->user->name.'</h2>';
echo "<p>".$posts->body."</p>";
//echo $posts->comments;
echo '<h3>Komentar :</h3>';
foreach ($posts->comments as $comment) {
echo $comment->body.'<br>';
}
echo '<h3>Tags :</h3>';
foreach ($posts->tags as $tag) {
echo '<a href="/tag/'. $tag->id .'">'.$tag->name.'</a><br>';
}
それは私にエラーを与える:
"Call to undefined relationship [tag] on model [App\Post]."
しかし、私は私」に変更しますポストモデルの中で機能する「タグ」は問題がなくなったばかりの「タグ」に変換されます。だから誰もこれについて何らかの名前のコンベンションを説明することができますか?ありがとう。詳細については、
は、ここで私のポストモデルです:
class Post extends Model
{
/**
* Get the comments for the blog post.
*/
public function comments()
{
return $this->hasMany('App\Comment');
}
public function user(){
return $this->belongsTo('App\User');
}
public function tags(){
return $this->belongsToMany('App\Tag');
}
}
あなたのPOSTモデルも投稿してください。 –
が完了しました。私は私のモデルを質問に追加しました。 – Ying
あなたの関係は 'tags'ではなく 'tags'という名前だったので... with()で関係名を使用します。しかし、一貫性を保つために、名前を付けることができます。 – Devon