如何在查找表中删除这些额外的条目?

时间:2016-10-18 11:58:07

标签: laravel laravel-5 eloquent

我正在制作一个简单的后端,将照片添加到我的网站。每张照片可以分为多个类别,并且有多种尺寸,因此我有查找表可以将照片,类别和尺寸加在一起。

这是我填充查找表的代码:

"category" => array:3 [▼
        0 => "1"
        1 => "2"
        2 => "3"
      ]
      "size" => array:4 [▼
        0 => "1"
        1 => "2"
        2 => "3"
        3 => "4"
      ]

以下是请求中传递的数据示例:

id  photo_id  category_id
85  55        1
86  55        85
87  55        2
88  55        87
89  55        3
90  55        89

但是,虽然插入工作并且填充了查找表,但每隔一个插入的行都包含先前插入的条目的id,例如:

function product_thumbnail_url($pid){
$image_id = get_post_thumbnail_id($pid);  
$image_url = wp_get_attachment_image_src($image_id,'screen-shot');  
return  $image_url[0];  
}

function list_my_images_slots( $cpt = false ){
$list_images = apply_filters('list_images',array(
    'image1' => '_image1',
    'image2' => '_image2',
    'image3' => '_image3',
    'image4' => '_image۴',
    'image5' => '_image5',
    'image6' => '_image6',
    'image7' => '_image7',
    'image8' => '_image8',
    'image9' => '_image9',
    'image10'=> '_image10',
    ), $cpt );
    return $list_images;
    }

add_action("admin_init", "add_image_metabox");
function add_image_metabox(){
add_meta_box('elnazimage', __('گالری تصاویر'), "elnazimage", 'startup',     'normal', 'core');
//add_meta_box('elnazimage', __('گالری تصاویر'), "elnazimage", 'opportunities', 'normal', 'core');
}


add_action('save_post', 'save_image_metabox'); 
function save_image_metabox($post_ID){ 
// on retourne rien du tout s'il s'agit d'une sauvegarde automatique
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
    return $post_id;

$list_images = list_my_images_slots();
foreach($list_images as $k => $i){
    if ( isset( $_POST[$k] ) ) {
        check_admin_referer('image-liee-save_'.$_POST['post_ID'], 'image-liee-nonce');
        update_post_meta($post_ID, $i, esc_html($_POST[$k])); 
    }
    }
}


function elnazimage($post){
$list_images = list_my_images_slots();

wp_enqueue_script( 'media-upload' );
wp_enqueue_script( 'thickbox' );
wp_enqueue_script( 'quicktags' );
wp_enqueue_script( 'jquery-ui-resizable' );
wp_enqueue_script( 'jquery-ui-draggable' );
wp_enqueue_script( 'jquery-ui-button' );
wp_enqueue_script( 'jquery-ui-position' );
wp_enqueue_script( 'jquery-ui-dialog' );
wp_enqueue_script( 'wpdialogs' );
wp_enqueue_script( 'wplink' );
wp_enqueue_script( 'wpdialogs-popup' );
wp_enqueue_script( 'wp-fullscreen' );
wp_enqueue_script( 'editor' );
wp_enqueue_script( 'word-count' );
wp_enqueue_script( 'img-mb', get_template_directory_uri() . '/js/get-images.js', array( 'jquery','media-upload','thickbox','set-post-thumbnail' ) );
wp_enqueue_style( 'thickbox' );

wp_nonce_field( 'image-liee-save_'.$post->ID, 'image-liee-nonce');

echo '<div id="droppable">';
$z =1;
foreach($list_images as $k=>$i){
    $meta = get_post_meta($post->ID,$i,true);
    $img = (isset($meta)) ? '<img id="image-prev'.$z.'" src="'.$meta.'" width="100" height="100" alt="" draggable="false">' : '';
    echo '<div class="image-entry" draggable="true">';
    echo '<input type="text" name="'.$k.'" id="'.$k.'" class="id_img" value="'.$meta.'">';
    echo '<div class="img-preview">'.$img.'</div>';
    echo '<a href="javascript:void(0);" class="get-image button-secondary" data-num="'.$z.'">'._x('Add New','file').'</a><a href="javascript:void(0);" class="del-image button-secondary" data-num="'.$z.'">'.__('Delete').'</a>';
    echo '</div>';
    $z++;
}
echo '</div>';
?>

<div style="clear:left;"></div>
<script>jQuery(document).ready(function($){
    function reorderImages(){
        //reorder images
        $('#droppable .image-entry').each(function(i){
            //rewrite attr
            var num = i+1;
            $(this).find('.get-image').attr('data-num',num);
            $(this).find('.del-image').attr('data-num',num);
            $(this).find('div.img-preview').attr('data-num',num);
            var $input = $(this).find('input');
            $input.attr('name','image'+num).attr('id','image'+num).attr('data-num',num);
        });
    }

    if('draggable' in document.createElement('span')) {
        function handleDragStart(e) {
          this.style.opacity = '0.۴';  // this / e.target is the source node.
        }

        function handleDragOver(e) {
          if (e.preventDefault) {
            e.preventDefault(); // Necessary. Allows us to drop.
          }
          e.dataTransfer.dropEffect = 'move';  // See the section on the DataTransfer object.
          return false;
        }

        function handleDragEnter(e) {
          // this / e.target is the current hover target.
          this.classList.add('over');
        }

        function handleDragLeave(e) {
            var rect = this.getBoundingClientRect();
           // Check the mouseEvent coordinates are outside of the rectangle
           if(e.x > rect.left + rect.width || e.x < rect.left
           || e.y > rect.top + rect.height || e.y < rect.top) {
               this.classList.remove('over');  // this / e.target is previous target element.
           }
        }

        function handleDrop(e) {
          // this / e.target is current target element.
          if (e.stopPropagation) {
            e.stopPropagation(); // stops the browser from redirecting.
          }
          // Don't do anything if dropping the same column we're dragging.
          if (dragSrcEl != this) {
            // Set the source column's HTML to the HTML of the column we dropped on.
            dragSrcEl.innerHTML = this.innerHTML;
            this.innerHTML = e.dataTransfer.getData('text/html');
            reorderImages();
          }
          // See the section on the DataTransfer object.
          return false;
        }

        function handleDragEnd(e) {
          // this/e.target is the source node.
          this.style.opacity = '1';
          [].forEach.call(cols, function (col) {
            col.classList.remove('over');
          });
        }

        var dragSrcEl = null;

        function handleDragStart(e) {
          // Target (this) element is the source node.
          this.style.opacity = '0.4';
          dragSrcEl = this;
          e.dataTransfer.effectAllowed = 'move';
          e.dataTransfer.setData('text/html', this.innerHTML);
        }

        var cols = document.querySelectorAll('#droppable .image-entry');
        [].forEach.call(cols, function(col) {
          col.addEventListener('dragstart', handleDragStart, false);
          col.addEventListener('dragenter', handleDragEnter, false);
          col.addEventListener('dragover', handleDragOver, false);
          col.addEventListener('dragleave', handleDragLeave, false);
          col.addEventListener('drop', handleDrop, false);
          col.addEventListener('dragend', handleDragEnd, false);
        });
    }else{
          $( "#droppable" ).sortable({
            opacity: 0.4, 
            cursor: 'move',
            update: function(event, ui) {
                reorderImages()
            }
          });
    }
});</script>
<style type="text/css">
[draggable] {
  -moz-user-select: none;
  -khtml-user-select: none;
  -webkit-user-select: none;
  user-select: none;
}
.img-preview{
    position:relative;
    display:block;
    width:100px;
    height:100px;
    background:#efefef;
    border:1px solid #FFF;
}
.img-preview img{
    position:absolute;
    top:0;
    left:0;
}
.image-entry{
    float:left;
    margin:0 10px 10px 0;
    border:2px solid #ccc;
    padding:10px;
    background:#FFF;
}
.image-entry:last-child{margin-right:0;}
.image-entry.over{
    border: 2px dashed #000;
}
.get-image,.del-image{
    margin-top:10px !important;
    display:block !important;
}
</style>
<?php
}



function get_images_ids($thumbnail = false, $id = false){
global $post;
$the_id = ($id) ? $id : $post->ID;

$list_images = list_my_images_slots( get_post_type( $id ) );

$a = array();
foreach ($list_images as $key => $img) {
    if($i = get_post_meta($the_id,$img,true))
        $a[$key] = $i;
}
if($thumbnail){
    $thumb_id = get_post_thumbnail_id($the_id);
    if(!empty($thumb_id)) array_unshift($a, get_post_thumbnail_id($the_id));
} 
return $a;
}


function get_images_src($size = 'medium',$thumbnail = false, $id = false){
if($id)
    $images = $thumbnail ? get_images_ids(true,$id) :     get_images_ids(false,$id);
else 
    $images = $thumbnail ? get_images_ids(true) : get_images_ids();

foreach($images as $k => $i)
    $o= wp_get_attachment_image_src($i, $size);
return $o;
}


function get_multi_images_src($small = 'thumbnail',$large = 'full',$medium = 'medium',$thumbnail = false, $id = false){
if($id)
    $images = $thumbnail ? get_images_ids(true,$id) :     get_images_ids(false,$id);
else 
    $images = $thumbnail ? get_images_ids(true) : get_images_ids();
$o = array();
foreach($images as $k => $i) { 
$pic = wp_get_attachment_image_src($i,$large);
echo '<div class="col-md-4 gallery"><div class="pgallery-item"><a     rel="prettyPhoto[elnaz]" href="'.$pic[0].'">';
    echo '<img src="'.$pic[0].'" width="'.$pic[1].'" height="'.$pic[2].'"     />';
    echo '<span>'.get_the_title($i).'</span>';
    echo '</a></div></div>';
 }

$list_images = list_my_images_slots();
foreach($list_images as $k => $i){
        $pic = wp_get_attachment_image_src($i,$large);
echo '<div class="col-md-4 gallery"><div class="pgallery-item"><a     rel="prettyPhoto[elnaz]" href="'.$pic[0].'">';
    echo '<img src="'.$pic[0].'" width="'.$pic[1].'" height="'.$pic[2].'" />';
    echo '<span>'.get_the_title($i).'</span>';
    echo '</a></div></div>';

}
return '';
}

}

发生了什么以及如何解决?

1 个答案:

答案 0 :(得分:1)

您不应在数据透视表中创建新条目。相反,您可以使用attach()

foreach($request->category as $category)
{
    $photo->categories()->attach($category);
    // ----- OR ---------
    $cat = Category::where('id',$category)->first();
    $photo->categories()->save($cat);
}

您可以阅读laravel文档here

中的更多内容