私はcontents_categories
とcontent
BelongsToMany()
関係船とテーブルLaravel GET、POSTカテゴリ私のデータベース内
Contents
あります
class Contents extends Model
{
protected $table = 'contents';
protected $guarded = ['id'];
public function categories()
{
return $this->belongsToMany(ContentCategories::class);
}
}
ContentCategories
:
class ContentCategories extends Model
{
protected $table = 'contents_categories';
protected $guarded = ['id'];
public function contents()
{
return $this->belongsToMany(Contents::class);
}
}
使用このコードは、contents
のテーブルに選択した複数のケイト血みどろの仕事の罰金とそれが今content_categories_contents
public function store(RequestContents $request)
{
$data = Contents::create([
'title' => $request->title,
'lang' => $request->_language,
'type' => $request->type,
'description' => $request->description,
'featured_images' => '',
'visit' => 0,
]);
$data->categories()->attach($request->categories);
}
としてデータベースおよびピボットテーブルに保存することができます!残念ながら、私は結果でそれらを持っていけないコンテンツのカテゴリを取得するには、このコードを使用しようとすると:
public function show($id)
{
$content = Contents::find($id);
$selected_categories = $content->categories();
dd($selected_categories);
}
結果:
BelongsToMany {#208 ▼
#table: "content_categories_contents"
#foreignPivotKey: "contents_id"
#relatedPivotKey: "content_categories_id"
#parentKey: "id"
#relatedKey: "id"
#relationName: "categories"
#pivotColumns: []
#pivotWheres: []
#pivotWhereIns: []
#pivotCreatedAt: null
#pivotUpdatedAt: null
#using: null
#accessor: "pivot"
#query: Builder {#217 ▼
#query: Builder {#209 ▶}
#model: ContentCategories {#213 ▼
#table: "contents_categories"
#guarded: array:1 [▶]
#connection: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: false
+wasRecentlyCreated: false
#attributes: []
#original: []
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: []
}
#eagerLoad: []
#localMacros: []
#onDelete: null
#passthru: array:11 [▶]
#scopes: []
#removedScopes: []
}
#parent: Contents {#218 ▼
#table: "contents"
#guarded: array:1 [▶]
#connection: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: false
+wasRecentlyCreated: false
#attributes: []
#original: []
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: []
}
#related: ContentCategories {#213 ▶}
}
開きます結果で、この収集データ: '#related:CONTENTCATEGORIES {#213▶}'それは空のですか? –