Привет
Прости
Я не очень хорошо владею английским языком;
поиск работает со связанными моделями
но когда я хочу отсортировать как связанное поле, оно дублируется
потому что перевод предложения where не применяется при сортировке
любое решение?
class OrderFood extends Model
{
protected $table = 'order_foods';
protected $fillable = [
'order_id','food_id','quantity','food_price'
];
public function order()
{
return $this->belongsTo(Order::class);
}
public function food()
{
return $this->belongsTo(Food::class)
->with('translate');
}
}
class Food extends Model
{
protected $table = 'foods';
protected $fillable = [
'title','date','tax','tax_enabled','tax_included','images','star','description','recipes','status','lang'
];
public function translate()
{
return $this->hasOne(FoodTranslator::class,'food_id')
->where('lang',app()->getLocale());
}
}
public function query()
{
DB::statement(DB::raw('set @rownum=0'));
DB::statement(DB::raw('SET collation_connection = utf8_general_ci'));
DB::statement(DB::raw('SET character_set_connection = utf8'));
$order_id = $this->order_id;
$order_foods = Order::find($order_id)->foods()->with(['food.translate'])->select(['*','order_foods.created_at',DB::raw('<strong i="5">@rownum</strong> := <strong i="6">@rownum</strong> + 1 AS rownum')]);
return $this->applyScopes($order_foods);
}
private function getColumns()
{
return [
['title' => trans('form.row'),'name' => 'rownum', 'data' => 'rownum','searchable'=>false],
['title' => trans('order.order_food'),'name' => 'food.translate.title', 'data' => 'food.translate.title','orderable'=>false],
['title' => trans('order.quantity'),'name' => 'quantity', 'data' => 'quantity'],
['title' => trans('order.food_price'),'name' => 'food_price', 'data' => 'food_price'],
['title' => trans('form.created_at'),'name' => 'created_at', 'data' => 'created_at'],
['title' => trans('form.action'),'name' => 'action', 'data' => 'action','searchable'=>false,'exportable'=>false,'printable'=>false],
];
}
Эта проблема уже исправлена в версии 8. Он совместим с Laravel 5.4, но имеет критические изменения. Обратите внимание, что он еще не отмечен как стабильный. Спасибо!
большое спасибо!
эта проблема не исправлена в версии 8
мне нужно изменить свои коды?
Проблема здесь в отношении перевода, верно?
public function translate()
{
return $this->hasOne(FoodTranslator::class,'food_id')
->where('lang',app()->getLocale());
}
Проблема в том, что пункт where не применяется? Это было решено в версии 8, если нет другой проблемы, которую я не вижу?
по заказу выполняется 3 запроса
1:
bindings:[]
query:"select count(*) as aggregate from (select '1' as `row_count` from `foods`) count_row_table"
time:0.29
2:
bindings:[]
query:"select *, <strong i="6">@rownum</strong> := <strong i="7">@rownum</strong> + 1 AS rownum from `foods` left join `food_translator` on `food_translator`.`food_id` = `foods`.`id` order by `food_translator`.`title` desc limit 10 offset 0"
time:0.81
3:
bindings:["fa", 1]
query:"select * from `food_translator` where `lang` = ? and `food_translator`.`food_id` in (?)"
time:0.46
возможно, где предложение должно быть во втором запросе, а не в 3
этот запрос
query:"select * from `food_translator` where `lang` = ? and `food_translator`.`food_id` in (?)"
это для
public function translate()
{
return $this->hasOne(FoodTranslator::class,'food_id')
->where('lang',app()->getLocale());
}
это не влияет на результаты
@aliworkshop Я думаю, что сейчас вижу проблему. Буду копать дальше, когда у меня будет возможность.
спасибо большое, хозяин :)
ошибка не исправлена?
Я исправил проблему с редактированием класса EloquentDataTable в пространстве имен Yajra \ DataTables.
protected function joinEagerLoadedColumn($relation, $relationColumn)
{
$table = '';
$lastQuery = $this->query;
foreach (explode('.', $relation) as $eachRelation) {
$model = $lastQuery->getRelation($eachRelation);
$fillable = [];
switch (true) {
case $model instanceof BelongsToMany:
$pivot = $model->getTable();
$pivotPK = $model->getExistenceCompareKey();
$pivotFK = $model->getQualifiedParentKeyName();
$this->performJoin($pivot, $pivotPK, $pivotFK);
$related = $model->getRelated();
$table = $related->getTable();
$tablePK = $related->getForeignKey();
$foreign = $pivot . '.' . $tablePK;
$other = $related->getQualifiedKeyName();
$lastQuery->addSelect($table . '.' . $relationColumn);
$this->performJoin($table, $foreign, $other);
break;
case $model instanceof HasOneOrMany:
$table = $model->getRelated()->getTable();
$foreign = $model->getQualifiedForeignKeyName();
$other = $model->getQualifiedParentKeyName();
$fillable = $model->getRelated()->getFillable();
break;
case $model instanceof BelongsTo:
$table = $model->getRelated()->getTable();
$foreign = $model->getQualifiedForeignKey();
$other = $model->getQualifiedOwnerKeyName();
break;
default:
throw new Exception('Relation ' . get_class($model) . ' is not yet supported.');
}
$this->performJoin($table, $foreign, $other,'inner',$fillable);
$lastQuery = $model->getQuery();
}
return $table . '.' . $relationColumn;
}
protected function performJoin($table, $foreign, $other, $type = 'left', $fillable = [])
{
$joins = [];
foreach ((array) $this->getBaseQueryBuilder()->joins as $key => $join) {
$joins[] = $join->table;
}
if (! in_array($table, $joins)) {
$this->getBaseQueryBuilder()->join($table, $foreign, '=', $other, $type);
if (in_array('lang',$fillable))
$this->query->where('lang', app()->getLocale());
}
}
это изменение вручную применить lang
column where для присоединения к запросу
если бы существовал способ, то отношение, где пункты применялись бы как это
это было бы очень хорошо
@aliworkshop спасибо, но предложенное решение будет работать только в вашем случае. Можете ли вы попробовать, возможно, использовать приведенный ниже код?
Заменять:
$this->getBaseQueryBuilder()->join($table, $foreign, '=', $other, $type);
С участием:
$this->query->join($table, $foreign, '=', $other, $type);
Немного занят рабочими проектами и в последнее время не может уделять много времени работе с oss. Спасибо!
снова привет господин
я нахожу другое решение этой проблемы
если мы отредактируем класс EloquentDataTable в пространстве имен Yajra \ DataTables как это, он, вероятно, сработает
protected function joinEagerLoadedColumn($relation, $relationColumn)
{
$table = '';
$lastQuery = $this->query;
foreach (explode('.', $relation) as $eachRelation) {
$model = $lastQuery->getRelation($eachRelation);
switch (true) {
case $model instanceof BelongsToMany:
$pivot = $model->getTable();
$pivotPK = $model->getExistenceCompareKey();
$pivotFK = $model->getQualifiedParentKeyName();
$this->performJoin($pivot, $pivotPK, $pivotFK);
$related = $model->getRelated();
$table = $related->getTable();
$tablePK = $related->getForeignKey();
$foreign = $pivot . '.' . $tablePK;
$other = $related->getQualifiedKeyName();
$lastQuery->addSelect($table . '.' . $relationColumn);
$this->performJoin($table, $foreign, $other);
break;
case $model instanceof HasOneOrMany:
$table = $model->getRelated()->getTable();
$foreign = $model->getQualifiedForeignKeyName();
$other = $model->getQualifiedParentKeyName();
break;
case $model instanceof BelongsTo:
$table = $model->getRelated()->getTable();
$foreign = $model->getQualifiedForeignKey();
$other = $model->getQualifiedOwnerKeyName();
break;
default:
throw new Exception('Relation ' . get_class($model) . ' is not yet supported.');
}
$wheres = $model->getQuery()->getQuery()->wheres;
$this->performJoin($table, $foreign, $other,'inner',$wheres);
$lastQuery = $model->getQuery();
}
return $table . '.' . $relationColumn;
}
protected function performJoin($table, $foreign, $other, $type = 'left', $wheres = [])
{
$joins = [];
foreach ((array) $this->getBaseQueryBuilder()->joins as $key => $join) {
$joins[] = $join->table;
}
if (! in_array($table, $joins)) {
$this->query->join($table, $foreign, '=', $other, $type);
foreach ($wheres as $where) {
if ($where['boolean'] == 'and')
$this->query->where($where['column'], $where['operator'], $where['value']);
else
$this->query->orWhere($where['column'], $where['operator'], $where['value']);
}
}
}
пожалуйста, примените этот код в следующей версии