はじめに
コード
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
use HasFactory;
public function article_categories()
{
return $this->hasMany('App\Models\ArticleCategory');
}
public function user()
{
print "test";
return $this->belongsTo('App\Models\User', 'foreign_key');
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
use HasFactory;
public function article_categories()
{
return $this->hasMany('App\Models\ArticleCategory');
}
public function user()
{
print "test";
return $this->belongsTo('App\Models\User', 'foreign_key');
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class ArticleCategory extends Model
{
use HasFactory;
public function category()
{
return $this->belongsTo('App\Models\Category', 'foreign_key', 'category_id');
}
public function article()
{
return $this->belongsTo('App\Models\Article', 'foreign_key');
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
use HasFactory;
public function article_categories()
{
return $this->hasMany('App\Models\ArticleCategory');
}
}
確認
- tinkerで確認するとリレーションしてデータが取得できている事は確認できるが、全部のパターンで検証できていないので上記の設定にミスがあったら、ご指摘ください
>>> $articles = App\Models\User::find(1)->articles[0]->article_categories[0]
=> App\Models\ArticleCategory {#4357
id: 2,
category_id: 1,
article_id: 3,
created_at: "2020-10-08 08:48:35",
updated_at: "2020-10-08 08:48:35",
}