属于很多关系,返回空数组,但修补匠显示数据

时间:2018-11-17 20:39:35

标签: php laravel eloquent

我正在尝试使用 belongsToMany 关系,我从没遇到任何问题,但是由于某种原因,现在它返回了空值。

但是,如果我与修补匠进行了核对,我将获得包含返回数据的数组

我已经在User模型中建立了这样的关系:

// linking with table tag
public function tags(){
    return $this->belongsToMany('App\Tag','tag_user','user_id','tag_id');
}

标记模型:

 public function user(){
    return $this->belongsToMany('App\User','tag_user','tag_id','user_id');
}

PostController

public function create()
{
    // bringing user details to show his preferneces
    $user_id = Auth::user()->user_id;
    $user = User::find($user_id)->first();

    //post_types
    $types= PostType::pluck('name', 'post_type_id');

    return view('user.create_post')->with('user', $user)->with('types',$types);
}

视图中

@foreach ($user->tags as $tag)

           <label class = "btn btncategory">
                  <input type = "checkbox"
                         name = "tag_selected[]"
                         value = "{{$tag->tag_id}}" >
                   {{$tag->tag_name}}
           </label>
@endforeach 

迁移

标签

        Schema::create('tags', function (Blueprint $table) {
            $table->increments('tag_id');
            $table->string('tag_name')->unique();
            $table->integer('type');
            $table->integer('used_time')->default('0');
            $table->timestamps();
        });

        Schema::create('tag_user', function(Blueprint $table){
            $table->integer('user_id');
            $table->integer('tag_id');
            $table->primary(['user_id', 'tag_id']);
        });

用户

    Schema::create('users', function (Blueprint $table) {
        $table->increments('user_id');
        $table->string('user_name')->unique();
        $table->string('fname')->nullable();
        $table->string('lname')->nullable();
       ... etc etc

0 个答案:

没有答案