Как использовать Group by query в laravel? - PullRequest
0 голосов
/ 06 июня 2019

это то, как данные отображаются , но я хочу

Rhugveda desai -> цветы, сари, прасад

В моем приложении янужно использовать группу по предложению.Но я получаю синтаксическую ошибку. Кроме того, что я должен делать, если я хочу, чтобы столбец количества был умножен на количество, чтобы получить итог?Мои таблицы - это inkind и inkind_items, где inkind.id - это внешний ключ в таблице inkind_items как inkind_id.

SQLSTATE [42000]: синтаксическая ошибка или нарушение прав доступа: 1055 Выражение № 11 списка SELECT отсутствует в предложении GROUP BY и содержит неагрегированный столбец

моя таблица inkind_items inkind_items мой стол с чернилами inkind Мой запрос:

$inkinds = DB::table('inkind')
     ->join('inkind_items', 'inkind.id', '=', 'inkind_items.inkind_id')
     ->select('inkind.*', 'inkind_items.*')
     ->groupBy('inkind_items.inkind_id')
     ->get();

Ответы [ 3 ]

3 голосов
/ 06 июня 2019

Попробуйте использовать group_concat()

$inkinds = DB::table('inkind')
     ->join('inkind_items', 'inkind.id', '=', 'inkind_items.inkind_id')
     ->select('inkind.*', DB::raw('group_concat(inkind_items.name) as items'))
     ->groupBy('inkind_items.inkind_id')
     ->get();

Здесь я предполагаю, что inkind имеет поле name, а inkind_items имеет поля items.

1 голос
/ 10 июня 2019

Привет.Сегодня вы задали другой вопрос (об отображении ввода, когда установлен определенный флажок) , но удалили его до того, как я отправил свой ответ, поэтому я решил вместо этого вставить сюда ответ:

Просто для начала, вот объяснение того, как использовать addEventListener и createElement для достижения желаемого результата.

Если какая-то его часть все еще неясна после изучениякод и сопровождающие комментарии, пожалуйста, поищите название все еще неясной функции на MDN .
(например, https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName.)

// Sets `box1` to refer to the first element on the page with the class "box".
const box1 = document.getElementsByClassName("box")[0];

// Sets `container` to be the element whose id attribute has the value "container".
//   (This is where our new input element, inside a new label element, will be added.)
const container = document.getElementById("container");

// Begins listening for clicks. From now on, whenever the user clicks anywhere
//   on the page, our listener will call the `noticeClick` function.
document.addEventListener("click", noticeClick);

function noticeClick(event){
  // Because this function's name is the second argument in 
  //   the call to `document.addEventListener`, above, it is
  //   automatically called every time a 'click' event happens on the 
  //   page (and it automatically receives that event as an argument.)
  // The "target" of the event is whatever the user clicked on.

  // So we set the variable `targ` to refer to this target, and we check whether:
  //   1) the clicked target is our checkbox,
  //   2) this click caused the checkbox to gain the "checked" attribute, and
  //   3) we have not already given the checkbox the "added" class
  const targ = event.target;
  if(targ.id == "box1" && targ.checked && !targ.classList.contains("added")){

  // If all three conditions are met, we...
    // ...set two variables, `label` and `val`
    const label = event.target.id;
    const val = event.target.value;

    // ...call the `createInput` function, passing these variables as its two arguments
    createInput(label, val);

    // ...give the checkbox the "added" class (so we can avoid accidentally adding it again)
    targ.classList.add("added");
  }
}

function createInput(newLabel, newValue){
  // When the user has checked our checkbox, the `noticeClick` function
  //   will call this function, which receives two arguments (which we can   
  //   see, by examining the `noticeClick` function, are two strings: the  
  //   `id` attribute of box1 and the `value` attribute of box1.)
  
  // We use `document.creatElement` to create an `input` element and a 
  //   `label` element, and `document.createTextNode` to set some text 
  //   to be used in the label (using the "newLabel" argument.)
  const myInput = document.createElement("input");
  const myLabel = document.createElement("label");
  const myLabelText = document.createTextNode(newLabel + " ");

  // We set our new `input` element's value using the "newValue" argument.
  myInput.value = newValue;

  // We use `appendChild` to put both the text and the input element
  //   inside the label, and to put the label inside `container`.
  myLabel.appendChild(myLabelText);
  myLabel.appendChild(myInput);
  container.appendChild(myLabel);
}


// This process can be applied to multiple checkboxes on the same page 
//   by adding a loop inside the `noticeClick` function, where the string
//   "box1" should be replaced with a variable that can refer to the id of a
//   different checkbox's `id` for each iteration of the loop.
<label>
  <input type="checkbox" id="box1" class="box" value="value1" />
  Label for box1
</label>
<hr />
<div id="container"></div>
0 голосов
/ 06 июня 2019

Для этого вы можете использовать методы сбора Laravel.

Просто позвоните:

$inkinds->groupBy('inkind_id'); 

после -> get ().Учитывая, что inkind_id является уникальным столбцом для обеих таблиц

...