Answers for "laravel has many"

PHP
3

has many through laravel

class Country extends Model
{
    public function posts()
    {
        return $this->hasManyThrough(
            'App\Post',
            'App\User',
            'country_id', // Foreign key on users table...
            'user_id', // Foreign key on posts table...
            'id', // Local key on countries table...
            'id' // Local key on users table...
        );
    }
}

when
countries
    id - integer
    name - string

users
    id - integer
    country_id - integer
    name - string

posts
    id - integer
    user_id - integer
    title - string
Posted by: Guest on June-28-2020
1

laravel has many

public function comments()
 {
   return $this->hasMany(Comment::class);
 }
Posted by: Guest on June-03-2021
7

belongs to many laravel

For example, a blog post may have an infinite number of comments. And a single
comment belongs to only a single post  

class Post extends Model
{
    public function comments()
    {
        return $this->hasMany('App\Models\Comment');
    }
}

class Comment extends Model
{
    public function post()
    {
        return $this->belongsTo('App\Models\Post');
    }
}
Posted by: Guest on October-16-2020
0

laravel has many

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    /**
     * Get the comments for the blog post.
     */
    public function comments()
    {
        return $this->hasMany('App\Models\Comment');
    }
}
Posted by: Guest on October-27-2020
0

laravel how to query belongsTo relationship

$movies = Movie::whereHas('director', function($q) {
    $q->where('name', 'great');
})->get();
Posted by: Guest on October-12-2020
1

eloquent relationships

$roles = App\User::find(1)->roles()->orderBy('name')->get();
Posted by: Guest on June-15-2020

Code answers related to "laravel has many"

Browse Popular Code Answers by Language