Laravel 5.4 - 多对多 - 选择表格 - 数据库链接

时间:2017-09-07 18:38:29

标签: php mysql eloquent many-to-many laravel-5.4

我正在练习Laravel并为活动假期建立一个博客。

我有一个描述假期的帖子表,然后是一个只有活动名称的活动表。我有一个连接表,它们之间的链接。这两个表共享多对多关系。我正在努力实现的是,我想在添加帖子时使用选择表单在表格中添加一个或多个活动。目前它没有注册活动表,而是在我的博客上创建帖子。

如果有任何建议和帮助,我将不胜感激

请参阅下面的代码:

// App \ ActivityController

<?php
namespace App\Http\Controllers;

use App\Activity;
use Illuminate\Http\Request;

class ActivityController extends Controller
{
    protected $fillable = [
      'activity_name'
    ];

    public function posts()
    {
        return $this->belongsToMany('App\Post')->using('App\activityPost')->withTimestamps();

    }
    public function index(Activity $activity)
    {
      $posts = $activity->posts;
      return view('posts.index', compact('posts'));
    }

    public function edit(Activity $activity)
    {

        $posts = App\Post::get()->pluck('title','body','id')->sortBy('title');
        return view('activities.edit', compact('activities', 'posts'));
    }
    public function update(Request $request, Activity $activity)
    {

        $activity->update($request->all());
        $activity->posts()->sync($request->posts);
        return redirect ('posts/create');
    }
    public function create()
    {

        return view('activities.create');
    }

    public function store()
    {
      $activity = new Activity;
      $activity->activity_name = request('activity_name');
      $activity->save();
      return redirect('activities/create');
    }

    public function show(Activity $activity)
    {
        return view ('activities.activity', ['Activity'=>$activity]);
    }
}


?>

// App \ PostController

<?php
namespace App\Http\Controllers;

use App\Post;
use Carbon\Carbon;
use Illuminate\Http\Request;


class PostController extends Controller
{

    public function __contruct()
    {
        $this->middleware('auth')->except(['index', 'show']);
    }
    public function index()
    {
        $posts = Post::latest()->get();

        return view('posts.index', compact('posts'));
    }

    public function show(Post $post)

    {
        return view('posts.show', compact('post'));
    }

    public function create()
    {
      $activities = \App\Activity::pluck('activity_name', 'activity_name');
        return view('posts.create', compact('activities'));


    }

    public function store(Request $request)
    {
        $this->validate(request(), [
            'title' => 'required',
            'body' => 'required',

        ]);
      Post::create([
        'title' =>request('title'),
        'body' =>request('body'),
        'user_id' => auth()->id()
      ]);



        return redirect('/');
    }
        public function activities()
    {
        return $this->belongsToMany('App\Activity')->using('App\activityPost');
    }
        public function update(Request $request, Post $post)
    {
        $post->update($request->all());
        $post->activities()->sync($request->activities);
        return redirect('post');
    }



}

?>

//应用\ post.php中

<?php
namespace App;

class Post extends Model

{


    public function countries()
    {
        return $this->hasMany(Country::class);
    }
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
    public function user()
    {
        return $this->belongsTo(User::class);
    }
    public function addComment($body)
    {
        $this ->comments()->create(compact('body'));
    }
    public function activities()
    {
        return $this->belongsToMany('App\Activity');
    }


}

&GT;

// App \ Activity.php

<?php
namespace App;


class Activity extends Model
{
    protected $table = 'activities';
    protected $fillable = ['activity_name'];

    public function posts()
    {
        return $this->belongsToMany('App\Post');
    }
    public function index()
    {
        $activities = Activity::orderBy('activity_name', 'asc')->paginate(10);
        return view('activities.index', ['activities'=>$activities]);
    }
    public function store()
    {
        return $this->belongsToMany('App\Post');
    }


    public function getRouteKeyName()
    {
        return 'activity_name';
    }

    public function create()
    {
        return view ('activities.create');
    }


}


?>

// Routes \ web.php

<?php


Route::get('/', 'PostController@index')->name('home');
Route::get('/posts/create', 'PostController@create');
Route::post('/posts', 'PostController@store');
Route::get('/posts/{post}', 'PostController@show');
Route::resource('posts', 'PostController');

Route::get('/about', 'AboutController@index');

Route::get('/logout', 'LoginController@destroy');

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

Route::post('posts/{post}/comments', 'CommentController@store');

Route::get('/posts/activities/{activity}', 'ActivityController@index');
Route::resource('activities', 'ActivityController');
Route::get('/activities/create', 'ActivityController@create');
Route::post('/activities', 'ActivityController@store');
Route::get('/activities/{activity}', 'ActivityController@show');
Route::put('/posts/create', 'ActivityController@update');

?>

// resources \ views \ posts.create.blade.php

<form method="POST" action="/posts">

{{csrf_field() }}

<div class="form-group">
    <label for="title">Name</label>
    <input type="text" class="form-control" id="title" name="title" required>
</div>

<div class="form-group">
    <label for="body">Description</label>
    <textarea name="body" id="body" class="form-control" required></textarea>
</div>


<!-- create form with select multiple
convert activity into array -->


<div class="form-group">
  <label for="activities">Select your Activity</label>
  <select class="form-control" name="activities" size="{{$activities->count()}}" required multiple>
    @foreach ($activities as $activity)
    <option value="activities">
      {{$activity}}
    </option>
        @endforeach
  </select>
</div>



<div class="form-group">
    <button type="submit" class="btn btn-primary">Publish</button>
</div>

</form>

// ActivityPost表

  public function up()
    {
        if(!Schema::hasTable('activity_post')) {
            Schema::create('activity_post', function (Blueprint $table)      {
                $table->integer('activity_id')->unsigned()->index();
                $table->foreign('activity_id')->references('id')->on('activities')->onDelete('cascade');

                $table->integer('post_id')->unsigned()->index();
                $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');

            });
        }
    }

//活动表

  public function up()
    {
        if(!Schema::hasTable('activities')) {
            Schema::create('activities', function (Blueprint $table) {
                $table->increments('id');
                $table->string('activity_name');
                $table->timestamps();
            });
        }
    }

//帖子表

public function up()
{
        if(!Schema::hasTable('posts')){
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id');
            $table->string('title');
            $table->text('body');
            $table->timestamps();
            });
        }
}

0 个答案:

没有答案