Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PHP

laravel hasmany

<?php
 
namespace AppModels;
 
use IlluminateDatabaseEloquentModel;
 
class Post extends Model
{
    /**
     * Get the comments for the blog post.
     */
    public function comments()
    {
      return $this->hasMany(Comment::class);
      //return $this->hasMany(Comment::class, 'foreign_key');
      //return $this->hasMany(Comment::class, 'foreign_key', 'local_key');
    }
}

// Other
use AppModelsPost;
 
$comments = Post::find(1)->comments;
 
foreach ($comments as $comment) {
    //
}
// Other
$comment = Post::find(1)->comments()
                    ->where('title', 'foo')
                    ->first();

 
PREVIOUS NEXT
Tagged: #laravel #hasmany
ADD COMMENT
Topic
Name
6+1 =