에 대한 열 이름을 무시하지 않습니다에 나는이 테이블이 있습니다많은 많은 Laravel 5.3 모델
을 그리고 나는이 모델이 : 나는를 조회하기 위해 노력하고있어
Video
Category
을 하나의 특정 카테고리에 속한 모든 비디오를 얻으려면 많은 관계로.
나는 경로 domain.dev/category/{category}
이 내 CategoryController
과 그의 해당 지점을 가리키고 있습니다. 나는 $request
을 통해 그것을 받고있다.
@foreach ($category->videos as $video) {
{{ $video->title }}
}
@endforeach
을하지만 Laravel 쿼리를 실행할 때 그것을 예외를 발생하고,
그것은videos.id
열처럼 보이는
QueryException in Connection.php line 769:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'videos.id' in 'on clause' (SQL: select `videos`.*, `videos_categories`.`category_id` as `pivot_category_id`, `videos_categories`.`video_id` as `pivot_video_id` from `videos` inner join `videos_categories` on `videos`.`id` = `videos_categories`.`video_id` where `videos_categories`.`category_id` is null)
, 오버라이드 (override)되지 않았다 (나는 videos
에서 NO id
필드가 없기 때문에, 난 당신이 마이그레이션에 볼 수 videos_id
을 사용하고,에 : 쿼리를 보여줍니다 모델. 모델의 키와 관계에서도 명시 적으로 재정의했습니다.
나는 ... 그 피벗 테이블의 알파벳 순서를 사용하는 것이 일반적인 관행이었다 알고하지 않았다 그리고 내 피벗 테이블은 "관례"그래서 나는 또한 테이블 이름의 오버라이드 (override)한다로 videos_categories
하지 categories_videos
입니다 관계.
내가 뭘 잘못하고 있는지, 왜 사용하지 않았는지 알 수없는 이유는 videos
입니다. id
그래서 도움이 필요합니다. 나 자신의 글을 쓰기 전에 다른 Q/A를 검색해 보았지만 어떤 해결책도 찾지 못했습니다. 여기
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Category;
class CategoryController extends Controller
{
/**
* Shows the Category page
*
* @return Response
*/
public function index(Request $request)
{
$category = Category::where('category', $request->category)->first();
// THINGS I TRIED
/*
$videos = $category->videos()->get();
foreach ($category->videos as $video) {
echo $video->title;
}
*/
return view('category.index', ['category' => $category]);
}
}
마이그레이션
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateVideosTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('videos', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('video_id')->unique();
$table->string('title', 255);
$table->string('embed_code', 255);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('videos');
}
}
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCategoriesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('category_id')->unique();
$table->string('category', 45);
$table->string('thumbnail');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('categories');
}
}
마이그레이션
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateVideosCategoriesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('videos_categories', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->integer('video_id')->unsigned()->nullable();
$table->integer('category_id')->unsigned()->nullable();
$table->foreign('video_id')
->references('video_id')
->on('videos')
->onUpdate('cascade')
->onDelete('cascade');
$table->foreign('category_id')
->references('category_id')
->on('categories')
->onUpdate('cascade')
->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('videos_categories', function (Blueprint $table) {
$table->dropForeign(['video_id', 'category_id']);
$table->dropColumn('video_id');
$table->dropColumn('category_id');
});
Schema::dropIfExists('videos_categories');
}
}
모델
,<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Video extends Model
{
protected $table = 'videos';
protected $primarykey = 'video_id';
public function categories() {
return $this->belongsToMany('App\Category', 'videos_categories', 'video_id', 'category_id');
}
public function tags() {
return $this->belongsToMany('App\Tag', 'videos_tags', 'video_id', 'tag_id');
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $table = 'categories';
protected $primarykey = 'category_id';
public $timestamps = false;
public function videos()
{
return $this->belongsToMany('App\Video', 'videos_categories', 'category_id', 'video_id');
}
}
복잡한 쿼리에서 서로 다른 테이블의 모호한 필드와 여러 개의 'id'필드를 피하기 위해 키를 ' _id'라는 이름으로 지정하는 것이 좋습니다. 많은 별칭을 만들어야합니다. 나에게 의미가 있었고 이것은 내가 한 일이다. 다른 한편으로, 왜 나는'id '를 사용하는 것이 더 나을지 이해하지 못한다. 아마 laravel 밖의 대회가 아니야 ... 내가 틀렸다면 나를 바로 잡으시오. –
Jeflopo
아, 답이 맞습니다. 그것은 $ primaryKey를 사용하여 작동합니다 : P Thank you !! – Jeflopo
나는 이것이 매우 유용 할 수 있다는 것을 이해하고 동의하지만,'category_title' 필드가있는 경우에 대비하여 다른 필드의 이름을'video_title'로 지정해야합니다. 맞습니까? 결국, 모든 것을 읽기가 더 어렵게 만들 것입니다. SQL 쿼리를 수동으로 수행하는 경우 열 이름 앞에'videos.id' 또는'categories.id'라는 접두사를 붙이면됩니다. 프레임 워크에서 (그리고 일반적으로 OO에서 말하면서), 당신은 당신의 필드에 다음과 같은 방식으로 접근 할 것이기 때문에, 더 의미가 없습니다 :'$ video-> video_id', 이것은 쓸모없는 반복입니다. 말하자면, 결국 그것은 중요하지 않다고 나는 믿는다. – AntoineB