Php 如何在Laravel Tastyigniter(在线食品订购)系统中显示特定于管理员的数据

Php 如何在Laravel Tastyigniter(在线食品订购)系统中显示特定于管理员的数据,php,laravel,Php,Laravel,我使用的是Laravel Tastyigniter系统,在该系统中,我希望根据当前登录的管理员添加的位置,在菜单模块的下拉列表中显示位置名称。 例如,如果管理员A添加了两个位置,如位置A和位置B和 管理员B添加了两个位置,例如位置C和位置D 注意-这些位置保存在数据库中,并带有created_by列,该列是添加位置的管理员id A) 会发生什么- 如果我以管理员A的身份登录,则位置下拉列表位置A和位置B应显示 如果我以管理员B的身份登录,那么位置下拉列表中的位置C和位置D应该显示 B)

我使用的是Laravel Tastyigniter系统,在该系统中,我希望根据当前登录的管理员添加的位置,在菜单模块的下拉列表中显示位置名称。
例如,如果管理员A添加了两个位置,如位置A和位置B和
管理员B添加了两个位置,例如位置C和位置D

  • 注意-这些位置保存在数据库中,并带有created_by列,该列是添加位置的管理员id
A) 会发生什么-

  • 如果我以管理员A的身份登录,则位置下拉列表位置A和位置B应显示
  • 如果我以管理员B的身份登录,那么位置下拉列表中的位置C和位置D应该显示
B) 目前发生了什么-

  • 对于这两个管理员,将显示所有4个位置
C) 下面是代码-

  • 这里是mensions\u model.php

    <?php namespace Admin\Models;
    
     use Admin\Traits\Locationable;
     use Igniter\Flame\Database\Traits\Purgeable;
     class Menus_model extends Model
     {
        use Purgeable;
        use Locationable;
    
        const LOCATIONABLE_RELATION = 'locations';
    
        public $relation = [
         'morphToMany' => [
             'locations' => ['Admin\Models\Locations_model', 'name' => 
              'locationable'],
          ],
        ];
    
        protected $purgeable = ['locations'];     
      }
    
小部件

  • 最后,还有一些用于输入字段的小部件,如选择、文本、收音机、复选框等。在我们的例子中,我们有小部件名称字段\u selectlist,它位于路径app/admin/widgets/form/field\u selectlist.php

  • 字段_selectlist.php文件的代码如下所示

    <?php 
       $fieldOptions = $field->options();
       //print_r($fieldOptions);die; All the locations are displaying here.
    
       $isCheckboxMode = $field->config['mode'] ?? 'checkbox';
       $selectMultiple = $isCheckboxMode == 'checkbox';
       $checkedValues = (array)$field->value;
       $enableFilter = (count($fieldOptions) > 20);
    ?>
    <div class="control-selectlist">
      <select
      data-control="selectlist"
      id="<?= $field->getId() ?>"
      name="<?= $field->getName() ?><?= $selectMultiple ? '[]' : '' ?>"
      <?php if ($field->placeholder) { ?>data-non-selected-text="<?= 
      e(lang($field->placeholder)) ?>"<?php } ?>
      <?= $selectMultiple ? 'multiple="multiple"' : '' ?>
      data-enable-filtering="<?= $enableFilter; ?>"
      data-enable-case-insensitive-filtering="<?= $enableFilter; ?>"
      <?= $field->getAttributes() ?>>
    
      <?php if ($field->placeholder) { ?>
          <option value=""><?= e(lang($field->placeholder)) ?></option>
      <?php } ?>
    
      <?php 
    
      foreach ($fieldOptions as $value => $option) { ?>
          <?php
          if (!is_array($option)) $option = [$option];
          if ($field->disabled AND !in_array($value, $checkedValues)) continue;
          ?>
          <option
              <?= in_array($value, $checkedValues) ? 'selected="selected"' : '' ?>
              value="<?= $value ?>">
              <?= e(is_lang_key($option[0]) ? lang($option[0]) : $option[0]) ?>
              <?php if (isset($option[1])) { ?>
                  <span><?= e(is_lang_key($option[1]) ? lang($option[1]) : 
                $option[1]) ?></span>
              <?php } ?>
          </option>
      <?php } ?>
    
    
    数据启用筛选=“”
    数据启用不区分大小写的筛选=“”
    >
    

位置和管理员之间的关系在哪里位置表中是否有用户id列是的,我在上面添加了注释,loations表中有一个created_by column,它的id是创建它的管理员。因此,您在哪里使用该created_by column来获取我正在搜索的位置?因为在这个tastyigniter系统中,模型中没有直接查询来获取记录。实际上,我可以提供帮助,但我需要更多代码、视图模板和位置模型
   <?php namespace Admin\Models;

    use Admin\Traits\HasDeliveryAreas;
    use Admin\Traits\HasWorkingHours;
    use Igniter\Flame\Database\Attach\HasMedia;
    use Igniter\Flame\Database\Traits\HasPermalink;
    use Igniter\Flame\Database\Traits\Purgeable;
    use Igniter\Flame\Location\Models\AbstractLocation;
    use DB;
    /**
      * Locations Model Class
      *
      * @package Admin
    */
  class Locations_model extends AbstractLocation
    {
      use HasWorkingHours;
      use HasDeliveryAreas;
      use HasPermalink;
      use Purgeable;
      use HasMedia;

      const LOCATION_CONTEXT_SINGLE = 'single';

      const LOCATION_CONTEXT_MULTIPLE = 'multiple';

      protected $appends = ['location_thumb'];

      protected $hidden = ['options'];

      public $casts = [
           'location_country_id' => 'integer',
           'location_lat' => 'double',
           'location_lng' => 'double',
           'offer_delivery' => 'boolean',
           'offer_collection' => 'boolean',
           'delivery_time' => 'integer',
           'collection_time' => 'integer',
           'last_order_time' => 'integer',
           'reservation_time_interval' => 'integer',
           'reservation_stay_time' => 'integer',
           'location_status' => 'boolean',
           'options' => 'serialize',
           'location_city' => 'integer',
           'region_id'=>'integer',
          ];

     public $relation = [
        'hasMany' => [
        'working_hours' => ['Admin\Models\Working_hours_model', 'delete' => 
         TRUE],
        'delivery_areas' => ['Admin\Models\Location_areas_model', 'delete' 
         => TRUE],
        'reviews' => ['Admin\Models\Reviews_model', 'delete' => TRUE],
    ],
    'belongsTo' => [
        'country' => ['System\Models\Countries_model', 'otherKey' => 
        'country_id', 'foreignKey' => 'location_country_id'],
        'city' => ['Admin\Models\City_model', 'otherKey' => 'city_id', 'foreignKey' => 'location_city'],
        'region' => ['Admin\Models\Region_model', 'otherKey' => 'region_id', 'foreignKey' => 'region_id'],
    ],
    'belongsToMany' => [
        'tables' => ['Admin\Models\Tables_model', 'table' => 'location_tables'],
        'cuisines' => ['Admin\Models\Cuisines_model', 'table' => 'location_cuisines'],
        
    ],
];

protected $purgeable = ['tables', 'delivery_areas','cuisines'];

public $permalinkable = [
    'permalink_slug' => [
        'source' => 'location_name',
        'controller' => 'local',
    ],
];

public $mediable = [
    'thumb',
    'gallery' => ['multiple' => TRUE],
];

protected static $allowedSortingColumns = [
    'distance asc', 'distance desc',
    'reviews_count asc', 'reviews_count desc',
    'location_id asc', 'location_id desc',
    'location_name asc', 'location_name desc',
];

public $url;

protected static $defaultLocation;

public static function onboardingIsComplete()
{
    if (!$defaultId = params('default_location_id'))
        return FALSE;

    if (!$model = self::isEnabled()->find($defaultId))
        return FALSE;

    return isset($model->getAddress()['location_lat'])
        AND isset($model->getAddress()['location_lng'])
        AND ($model->hasDelivery() OR $model->hasCollection())
        AND isset($model->options['hours'])
        AND $model->delivery_areas->where('is_default', 1)->count() > 0;
}

public function getWeekDaysOptions()
{
    return ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
}

//
// Events
//

protected function afterFetch()
{
    $this->parseOptionsValue();
}

protected function beforeSave()
{
    $this->parseOptionsValue();
}

protected function afterSave()
{
    $this->performAfterSave();
}

protected function beforeDelete()
{
    Location_tables_model::where('location_id', $this->getKey())->delete();
    Location_cuisines_model::where('location_id', $this->getKey())->delete();
}

//
// Scopes
//

/**
 * Scope a query to only include enabled location
 *
 * @return $this
 */
public function scopeIsEnabled($query)
{
    return $query->where('location_status', 1);
}

public function scopeListFrontEnd($query, array $options = [])
{
    extract(array_merge([
        'page' => 1,
        'pageLimit' => 20,
        'sort' => null,
        'search' => null,
        'latitude' => null,
        'longitude' => null,
    ], $options));

    if ($latitude AND $longitude)
        $query->selectDistance($latitude, $longitude);

    $searchableFields = ['location_name', 'location_address_1', 'location_address_2', 'location_city',
        'location_state', 'location_postcode', 'description'];

    if (!is_array($sort)) {
        $sort = [$sort];
    }

    foreach ($sort as $_sort) {
        if (in_array($_sort, self::$allowedSortingColumns)) {
            $parts = explode(' ', $_sort);
            if (count($parts) < 2) {
                array_push($parts, 'desc');
            }
            [$sortField, $sortDirection] = $parts;
            $query->orderBy($sortField, $sortDirection);
        }
    }

    $search = trim($search);
    if (strlen($search)) {
        $query->search($search, $searchableFields);
    }

    return $query->paginate($pageLimit, $page);
}

//
// Accessors & Mutators
//

public function getLocationThumbAttribute()
{
    return $this->hasMedia() ? $this->getThumb() : null;
}

public function getDeliveryTimeAttribute($value)
{
    return (int)$value;
}

public function getCollectionTimeAttribute($value)
{
    return (int)$value;
}

public function getFutureOrdersAttribute($value)
{
    return (bool)$value;
}

public function getReservationTimeIntervalAttribute($value)
{
    return (int)$value;
}

//
// Helpers
//

public function setUrl($suffix = null)
{
    if (is_single_location())
        $suffix = '/menus';

    $this->url = site_url($this->permalink_slug.$suffix);
}

public function hasGallery()
{
    return $this->hasMedia('gallery');
}

public function getGallery()
{
    $gallery = array_get($this->options, 'gallery');
    $gallery['images'] = $this->getMedia('gallery');

    return $gallery;
}

public function parseOptionsValue()
{
    $value = @unserialize($this->attributes['options']) ?: [];

    $this->parseHoursFromOptions($value);

    $this->parseAreasFromOptions($value);

    $this->attributes['options'] = @serialize($value);

    return $value;
}

public function listAvailablePayments()
{
    $result = [];

    $payments = array_get($this->options, 'payments', []);
    $paymentGateways = Payments_model::listPayments();

    foreach ($paymentGateways as $payment) {
        if ($payments AND !in_array($payment->code, $payments)) continue;

        $result[$payment->code] = $payment;
    }

    return collect($result);
}

public function performAfterSave()
{
    $this->restorePurgedValues();

    if (array_key_exists('hours', $this->options)) {
        $this->addOpeningHours($this->options['hours']);
    }

    if (array_key_exists('delivery_areas', $this->attributes)) {
        $this->addLocationAreas($this->attributes['delivery_areas']);
    }

    if (array_key_exists('tables', $this->attributes)) {
        $this->addLocationTables($this->attributes['tables']);
    }
    if (array_key_exists('cuisines', $this->attributes)) {
        $this->addLocationCuisines($this->attributes['cuisines']);
    }
}

public static function getDefault()
{
    if (self::$defaultLocation !== null) {
        return self::$defaultLocation;
    }

    $defaultLocation = self::isEnabled()->where('location_id', params('default_location_id'))->first();
    if (!$defaultLocation) {
        $defaultLocation = self::isEnabled()->first();
        if ($defaultLocation) {
            params('default_location_id', $defaultLocation->getKey());
            params()->save();
        }
    }

    return self::$defaultLocation = $defaultLocation;
}

/**
 * Create a new or update existing location tables
 *
 * @param array $tables
 *
 * @return bool
 */
   public function addLocationTables($tables = [])
   {
      return $this->tables()->sync($tables);
   }
   public function addLocationCuisines($cuisines = [])
   {
      return $this->cuisines()->sync($cuisines);
   }
 }
<?php

  $config['form']['tabs'] = [
    'defaultTab' => 'lang:admin::lang.locations.text_tab_general',
       'fields' => [
        'location_name' => [
          'label' => 'lang:admin::lang.label_name',
          'type' => 'text',
          'span' => 'left',
         ],
        'location_email' => [
        'label' => 'lang:admin::lang.label_email',
        'type' => 'text',
        'span' => 'right',
        ],
     'location_telephone' => [
       'label' => 'lang:admin::lang.locations.label_telephone',
       'type' => 'text',
       'span' => 'left',
     ],
    'location_status' => [
      'label' => 'lang:admin::lang.label_status',
      'type' => 'switch',
      'default' => 1,
      'span' => 'right',
    ],  
    'created_by' => [
      'type' => 'hidden',
      'default' => isset($_SESSION['user_id']) ? $_SESSION['user_id'] : '',
     ],
   ],
 ];

return $config;
<?php namespace Admin\Controllers;

use Admin\Classes\AdminController;
use Admin\Models\Menu_options_model;
use AdminMenu;
use ApplicationException;

 class Menus extends AdminController
 {
   public $implement = [
    'Admin\Actions\ListController',
    'Admin\Actions\FormController',
    'Admin\Actions\LocationAwareController',
 ];

public $listConfig = [
  'list' => [
      'model' => 'Admin\Models\Menus_model',
      'title' => 'lang:admin::lang.menus.text_title',
      'emptyMessage' => 'lang:admin::lang.menus.text_empty',
      'defaultSort' => ['menu_id', 'DESC'],
      'configFile' => 'menus_model',
  ],
 ];

protected $requiredPermissions = 'Admin.Menus';

 public function __construct()
{  
  parent::__construct();

  AdminMenu::setContext('menus');
 }

public function edit_onChooseMenuOption($context, $recordId)
{
  $menuOptionId = post('Menu._options');
  if (!$menuOption = Menu_options_model::find($menuOptionId))
      throw new ApplicationException('Please select a menu option to   
   attach');

  $model = $this->asExtension('FormController')->formFindModelObject($recordId);

  $menuItemOption = $model->menu_options()->create(['option_id' => $menuOptionId]);

  $menuOption->option_values()->get()->each(function ($model) use ($menuItemOption) {
      $menuItemOption->menu_option_values()->create([
          'menu_option_id' => $menuItemOption->menu_option_id,
          'option_value_id' => $model->option_value_id,
          'new_price' => $model->price,
      ]);
  });

  $model->reload();
  $this->asExtension('FormController')->initForm($model, $context);

  flash()->success(sprintf(lang('admin::lang.alert_success'), 'Menu item option attached'))->now();

  $formField = $this->widgets['form']->getField('menu_options');

  return [
      '#notification' => $this->makePartial('flash'),
      '#'.$formField->getId('group') => $this->widgets['form']->renderField($formField, [
          'useContainer' => FALSE,
      ]),
    ];
  }
}
 <?php namespace Admin\Controllers;

  use Admin\Facades\AdminLocation;
  use Admin\Models\Locations_model;
  use AdminMenu;
  use Exception;
  use Geocoder;

  class Locations extends \Admin\Classes\AdminController
  {
    public $implement = [
         'Admin\Actions\ListController',
        'Admin\Actions\FormController',
     ];

   public $listConfig = [
    'list' => [
      'model' => 'Admin\Models\Locations_model',
      'title' => 'lang:admin::lang.locations.text_title',
      'emptyMessage' => 'lang:admin::lang.locations.text_empty',
      'defaultSort' => ['location_id', 'DESC'],
      'configFile' => 'locations_model',
    ],
 ];


 protected $requiredPermissions = 'Admin.Locations';

 public function __construct()
 {
   parent::__construct();

  AdminMenu::setContext('locations', 'restaurant');
 }

public function remap($action, $params)
{
  if ($action != 'settings' AND AdminLocation::check())
      return $this->redirect('locations/settings');

  return parent::remap($action, $params);
}

public function settings($context = null)
{ 
  if (!AdminLocation::check())
      return $this->redirect('locations');

  $this->asExtension('FormController')->edit('edit', $this- 
  >getLocationId());
}

public function index_onSetDefault($context = null)
 {
  $defaultId = post('default');

  if (Locations_model::updateDefault(['location_id' => $defaultId])) {
      flash()->success(sprintf(lang('admin::lang.alert_success'), 
  lang('admin::lang.locations.alert_set_default')));
  }

  return $this->refreshList('list');
}

public function settings_onSave($context = null)
 {
  try {
      $this->asExtension('FormController')->edit_onSave('edit', 
    params('default_location_id'));

      return $this->refresh();
  }
  catch (Exception $ex) {
      $this->handleError($ex);
   }
}

 public function listOverrideColumnValue($record, $column, $alias = null)
  {
   if ($column->type != 'button')
      return null;

   if ($column->columnName != 'default')
      return null;

  $attributes = $column->attributes;
  $column->iconCssClass = 'fa fa-star-o';
  if ($record->getKey() == params('default_location_id')) {
      $column->iconCssClass = 'fa fa-star';
  }

  return $attributes;
 }

public function formExtendQuery($query)
{
  if ($locationId = $this->getLocationId())
      $query->where('location_id', $locationId);
}

public function formAfterSave($model)
{
  if (post('Location.options.auto_lat_lng')) {
      if ($logs = Geocoder::getLogs())
          flash()->error(implode(PHP_EOL, $logs))->important();
   }
  }
}
  <div class="row-fluid">
   <?= form_open(current_url(),
    [
      'id'     => 'edit-form',
      'role'   => 'form',
      'method' => 'POST',
   ]
 ); ?>

  <?= $this->renderForm(); ?>

  <?= form_close(); ?>
</div>
  public function renderForm($options = [])
   {
    if (!$this->formWidget) {
      throw new Exception(lang('admin::lang.form.not_ready'));
     }

    if (!is_null($this->toolbarWidget)) {
      $form[] = $this->toolbarWidget->render();
     }

    $form[] = $this->formWidget->render($options);

    return implode(PHP_EOL, $form);
  }
<?php 
   $fieldOptions = $field->options();
   //print_r($fieldOptions);die; All the locations are displaying here.

   $isCheckboxMode = $field->config['mode'] ?? 'checkbox';
   $selectMultiple = $isCheckboxMode == 'checkbox';
   $checkedValues = (array)$field->value;
   $enableFilter = (count($fieldOptions) > 20);
?>
<div class="control-selectlist">
  <select
  data-control="selectlist"
  id="<?= $field->getId() ?>"
  name="<?= $field->getName() ?><?= $selectMultiple ? '[]' : '' ?>"
  <?php if ($field->placeholder) { ?>data-non-selected-text="<?= 
  e(lang($field->placeholder)) ?>"<?php } ?>
  <?= $selectMultiple ? 'multiple="multiple"' : '' ?>
  data-enable-filtering="<?= $enableFilter; ?>"
  data-enable-case-insensitive-filtering="<?= $enableFilter; ?>"
  <?= $field->getAttributes() ?>>

  <?php if ($field->placeholder) { ?>
      <option value=""><?= e(lang($field->placeholder)) ?></option>
  <?php } ?>

  <?php 

  foreach ($fieldOptions as $value => $option) { ?>
      <?php
      if (!is_array($option)) $option = [$option];
      if ($field->disabled AND !in_array($value, $checkedValues)) continue;
      ?>
      <option
          <?= in_array($value, $checkedValues) ? 'selected="selected"' : '' ?>
          value="<?= $value ?>">
          <?= e(is_lang_key($option[0]) ? lang($option[0]) : $option[0]) ?>
          <?php if (isset($option[1])) { ?>
              <span><?= e(is_lang_key($option[1]) ? lang($option[1]) : 
            $option[1]) ?></span>
          <?php } ?>
      </option>
  <?php } ?>