xxxxxxxxxx
// hasMany
$this->hasMany(Model::class);
// invers
$this->belongsTo(Model::class);
xxxxxxxxxx
<?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(Comment::class);
//return $this->hasMany(Comment::class, 'foreign_key');
//return $this->hasMany(Comment::class, 'foreign_key', 'local_key');
}
}
// Other
use App\Models\Post;
$comments = Post::find(1)->comments;
foreach ($comments as $comment) {
//
}
// Other
$comment = Post::find(1)->comments()
->where('title', 'foo')
->first();
xxxxxxxxxx
return $this->hasMany('App\Comment', 'foreign_key');
return $this->hasMany('App\Comment', 'foreign_key', 'local_key');
xxxxxxxxxx
<?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(Comment::class);
}
}
xxxxxxxxxx
// function in model
public function hasManyFunction()
{
return $this->hasMany('App\Models\modelName', 'targetedId');
}
// get data with hasMany relation in controller
$data = Post::with('hasManyFunction')->find(1)->;
xxxxxxxxxx
$user->invoices()->create([
'service_id' => $orderId->service_id,
'review' => $request->review,
'stars' => $request->stars,
]);