简体   繁体   中英

Laravel save many to many relationship

Model

public function categories()
{
    return $this->belongsToMany('App\Category', 'post_categories');
}

public function posts()
{
    return $this->belongsToMany('App\Post', 'post_categories');
}

Controller

public $DEFAULT_LANGUAGE = 1;
public function store(Request $request)
{
    $titles = $request->PostTitle;
    $post = new Post();
    $post->PostTitle = $titles[$this->DEFAULT_LANGUAGE];
    $post->save();
    $post->categories()->attach($request->categoryID[$this->DEFAULT_LANGUAGE]);
    unset($titles[$this->DEFAULT_LANGUAGE]);
    foreach ($titles as $key => $title) {
        $post = new Post();
        $post->PostTitle = $request->PostTitle[$key];
        $post->save();
        $post->categories()->attach($request->categoryID[$key]);
    }

    return response()->json($post);

View

<select class="form-control category-list" name="categoryID[]" multiple="multiple" data-placeholder="Pilih Kategori">
    @foreach($categories as $category)
        <option value="{{ $category->id }}">
            {{ $category->CategoryName }}
        </option>
    @endforeach
</select>

If I have two categories and I want to select all the categories, why I only get the last category? I also tried to use foreach, but I got error offset. Any idea?

I have two tab pane.. I store two categoryID in tab 1 and one categoryID in tab 2.. then I click on submit button.. the header response two categoryID in tab 1, but in my database, I only got the last record

  • PostTitle[1]:sadasd
  • categoryID[1]:1
  • categoryID[1]:2
  • PostTitle[2]:asdasd
  • categoryID[2]:1

When I console, it shows two CategoryID..

https://i.stack.imgur.com/jBl2B.png

Attaching / Detaching

From the docs

Eloquent also provides a few additional helper methods to make working with related models more convenient. For example, let's imagine a user can have many roles and a role can have many users. To attach a role to a user by inserting a record in the intermediate table that joins the models, use the attach method:

You are passing only one value in attach and thus getting only the last record in order to get all you need to pass all categoryID

public $DEFAULT_LANGUAGE = 1;
public function store(Request $request)
{
    $titles = $request->PostTitle;
    $post = new Post();
    $post->PostTitle = $titles[$this->DEFAULT_LANGUAGE];
    $post->save();
    $post->categories()->attach($request->categoryID[$this->DEFAULT_LANGUAGE]);
    unset($titles[$this->DEFAULT_LANGUAGE]);
    $data= array();
    foreach ($titles as $key => $title) {
        $post = new Post();
        $post->PostTitle = $request->PostTitle[$key];
        $post->save();
        $data[]= $post->categories()->attach($request->categoryID[$key]);
    }

    return response()->json($data);

`

I have found the solution.. I only need to change the view

<select class="form-control category-list" name="categoryID[{{$language->id}}][]" multiple data-placeholder="Pilih Kategori">
  @foreach($categories as $category)
    <option value="{{$category->id}}">{{$category->CategoryName}}</option>
  @endforeach
</select>

and also change the controller

$post->categories()->attach($request->categoryID[$this->DEFAULT_LANGUAGE]);

For what are you using this model, what's it's name? Typically it's done that way: App\\Category:

public function posts()
{
    return $this->belongsToMany('App\Post', 'post_categories');
}

App\\Post:

public function categories()
{
    return $this->belongsToMany('App\Category', 'post_categories');
}

The two relationships are not in the same file, but in the two seperate models which are connected.

Try this one bro. I just change your code in controller. I wish it can help you :)

Model

public function categories()
{
    return $this->BelongsToMany('App\Category', 'post_categories');
}

public function posts()
{
    return $this->BelongsToMany('App\Post', 'post_categories');
}

Controller

$post = App\Post::findOrFail($id);
$post = $post->load('categories');
$attributes = $post->attributes->toArray();

View

<select class="form-control category-list" name="categoryID[]" multiple="multiple" data-placeholder="Pilih Kategori">
    @foreach($categories as $category)
        <option value="{{ $category->id }}">
            {{ $category->CategoryName }}
        </option>
    @endforeach
</select>

在您看来,尝试将multiple =“ multiple”更改为仅多个

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM