有一个表book_authors
链接两个表,books
并且authors
是多对多关系。该表book_authors
具有字段book_id
和author_id
。您需要创建迁移以更新这些字段并使它们独一无二,即 这样就不会有重复的条目,例如,不应该有:
id book_id author_id
1 1 2
2 1 2
...
请告诉我,这怎么办?
有一个表book_authors
链接两个表,books
并且authors
是多对多关系。该表book_authors
具有字段book_id
和author_id
。您需要创建迁移以更新这些字段并使它们独一无二,即 这样就不会有重复的条目,例如,不应该有:
id book_id author_id
1 1 2
2 1 2
...
请告诉我,这怎么办?
有一个用 lumen (laravel) 编写的后端连接到 redis。当我运行本地 php 和本地 redis 时,一切正常。当我通过 docker 运行时,我收到一个错误:Connection refused [tcp://127.0.0.1:6379]
. PHP 程序集(Dockerfile):
FROM php:7.2-fpm
RUN apt-get update \
&& chown -R www-data:www-data /var/www/html \
&& chmod -R 777 /var/www/html
RUN pecl install redis && docker-php-ext-enable redis
docker-compose.yml 文件:
nginx:
image: nginx:latest
ports:
- 127.0.0.1:80:80
volumes:
- .:/var/www/html
- ./docker/config/nginx:/etc/nginx/conf.d
- ./docker/logs/nginx:/var/log/nginx
links:
- php-fpm
php-fpm:
build:
context: ./docker/php-fpm
volumes:
- .:/var/www/html
redis:
image: redis
restart: always
ports:
- 127.0.0.1:6379:6379
logging:
driver: none
可能是什么问题呢?也许我没有打开一些端口?
我正在尝试在 symfony 上创建一个 REST API 服务(不使用 api 平台)。达到用户认证。我是否正确理解了算法?
1) Проходим обычную аутентификацию
2) Создаем apiKey и записываем его в бд
3) Возвращаем клиенту этот apiKey
4) При каждом обращении клиента к серверу проверяем валидность apiKey
?
如果是,如何正确执行?使用什么服务等等。从第一步开始。建议使用最少的第三方服务,但只能使用 symfony 开发人员自己推荐的服务
symfony 4 中有一个注释只允许POST
请求,如果没有发送请求,则会POST
出现标准的 symfony 错误。我怎样才能捕捉到这个错误,以便我可以将它返回为json
?
`/**
* @Route("/add_user", name="add_user", methods="POST")
*/`
在命令的帮助下make:auth
创建了授权。用用户填满表格。当我尝试登录时,我收到一条错误消息:
There is no user provider for user "App\Entity\User". Shouldn't the "supportsClass()" method of your user provider return true for this classname?
怎么了?似乎我按照文档https://symfony.com/doc/current/security/form_login_setup.html中的指示做了所有事情
我的安全.yaml
encoders:
App\Entity\User:
algorithm: bcrypt
cost: 12
# https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
providers:
in_memory: { memory: null }
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
anonymous: lazy
guard:
authenticators:
- App\Security\LoginFormAuthenticator
logout:
path: app_logout
# where to redirect after logout
# target: app_any_route
# activate different ways to authenticate
# https://symfony.com/doc/current/security.html#firewalls-authentication
# https://symfony.com/doc/current/security/impersonating_user.html
# switch_user: true
# Easy way to control access for large sections of your site
# Note: Only the *first* access control that matches will be used
access_control:
# - { path: ^/admin, roles: ROLE_ADMIN }
# - { path: ^/profile, roles: ROLE_USER }
Guard(表单处理)
namespace App\Security;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Csrf\CsrfToken;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
use Symfony\Component\Security\Guard\Authenticator\AbstractFormLoginAuthenticator;
use Symfony\Component\Security\Guard\PasswordAuthenticatedInterface;
use Symfony\Component\Security\Http\Util\TargetPathTrait;
class LoginFormAuthenticator extends AbstractFormLoginAuthenticator implements PasswordAuthenticatedInterface
{
use TargetPathTrait;
private $entityManager;
private $urlGenerator;
private $csrfTokenManager;
private $passwordEncoder;
public function __construct(EntityManagerInterface $entityManager, UrlGeneratorInterface $urlGenerator, CsrfTokenManagerInterface $csrfTokenManager, UserPasswordEncoderInterface $passwordEncoder)
{
$this->entityManager = $entityManager;
$this->urlGenerator = $urlGenerator;
$this->csrfTokenManager = $csrfTokenManager;
$this->passwordEncoder = $passwordEncoder;
}
public function supports(Request $request)
{
return 'app_login' === $request->attributes->get('_route')
&& $request->isMethod('POST');
}
public function getCredentials(Request $request)
{
$credentials = [
'email' => $request->request->get('email'),
'password' => $request->request->get('password'),
'csrf_token' => $request->request->get('_csrf_token'),
];
$request->getSession()->set(
Security::LAST_USERNAME,
$credentials['email']
);
return $credentials;
}
public function getUser($credentials, UserProviderInterface $userProvider)
{
$token = new CsrfToken('authenticate', $credentials['csrf_token']);
if (!$this->csrfTokenManager->isTokenValid($token)) {
throw new InvalidCsrfTokenException();
}
$user = $this->entityManager->getRepository(User::class)->findOneBy(['email' => $credentials['email']]);
if (!$user) {
// fail authentication with a custom error
throw new CustomUserMessageAuthenticationException('Email could not be found.');
}
return $user;
}
public function checkCredentials($credentials, UserInterface $user)
{
return $this->passwordEncoder->isPasswordValid($user, $credentials['password']);
}
/**
* Used to upgrade (rehash) the user's password automatically over time.
*/
public function getPassword($credentials): ?string
{
return $credentials['password'];
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
if ($targetPath = $this->getTargetPath($request->getSession(), $providerKey)) {
return new RedirectResponse($targetPath);
}
// For example : return new RedirectResponse($this->urlGenerator->generate('some_route'));
//throw new \Exception('TODO: provide a valid redirect inside '.__FILE__);
return new RedirectResponse($this->urlGenerator->generate('app_homepage'));
}
protected function getLoginUrl()
{
return $this->urlGenerator->generate('app_login');
}
}
PS在此之前,我在 UserProvider 中编辑了supportsClass,使其不返回false
:
{
return $class === UserIdentity::class;
}
有这样的html
<form action="/config/lang" method="POST" >
<select class="select_send_ajax selectpicker">
<option>1</option>
<option>2</option>
</select>
</form>
还有负责处理的js
$('.select_send_ajax').on('change', function () {
this.form.submit();
});
$('form').submit(function(event) { //Отправка всех форм
console.log(123);
event.preventDefault();
}
当我选择某些内容时,select
会立即发送表单,尽管我们已禁用表单提交。有必要选择时,select
表单会尝试走,但由于我们禁止它,它只会显示123
在控制台中
你好!有一个对返回所有产品的数据库的查询:
SELECT SQL_CALC_FOUND_ROWS
p.product_id as 'product_id',
p.image as 'p.image',
p.price as 'p.price',
pd.name as 'pd.name',
ms.seller_id as 'seller_id',
ms.nickname as 'ms.nickname',
mp.product_status as 'mp.product_status',
mp.product_approved as 'mp.product_approved',
mp.number_sold as 'mp.number_sold',
mp.list_until as 'mp.list_until',
p.date_added as 'p.date_created',
p.date_modified as 'p.date_modified',
pd.description as 'pd.description'
FROM oc_product p
INNER JOIN oc_product_description pd USING(product_id)
LEFT JOIN oc_ms_product mp USING(product_id)
LEFT JOIN oc_ms_seller ms USING (seller_id)
WHERE 1 = 1 AND ms.seller_id = 27 AND product_status IN (1)
GROUP BY p.product_id
HAVING 1 = 1
ORDER BY pd.name ASC LIMIT 0, 12
例如,您需要参考该表oc_product_to_category
(其中包含字段product_id
和category_id
)并仅使用 =1 的那些产品category_id
。我不知道该怎么做
你好!有要求
SELECT * FROM `product` LEFT JOIN `category_product` ON (product.category = category_product.id) WHERE (category_product.seo_url = 'category1')`
两个表都包含name
和seo_url
。问题是,我怎样才能明确指定应该从服务器上已经存在name
的表中获取什么?PS我尝试使用它但它不起作用(seo_url
product
as
你好!有一个显示所有产品的查询:
SELECT p.product_id,
(SELECT AVG(rating) AS total
FROM oc_review r1
WHERE r1.product_id = p.product_id AND r1.status = '1'
GROUP BY r1.product_id) AS rating,
(SELECT price
FROM oc_product_discount pd2
WHERE pd2.product_id = p.product_id
AND pd2.customer_group_id = '1'
AND pd2.quantity = '1'
AND ((pd2.date_start = '0000-00-00' OR pd2.date_start < NOW())
AND (pd2.date_end = '0000-00-00' OR pd2.date_end > NOW()))
ORDER BY pd2.priority ASC, pd2.price ASC LIMIT 1) AS discount,
(SELECT price
FROM oc_product_special ps
WHERE ps.product_id = p.product_id
AND ps.customer_group_id = '1'
AND ((ps.date_start = '0000-00-00' OR ps.date_start < NOW())
AND (ps.date_end = '0000-00-00' OR ps.date_end > NOW()))
ORDER BY ps.priority ASC, ps.price ASC LIMIT 1) AS special
FROM oc_product_to_category p2c
LEFT JOIN oc_product p ON (p2c.product_id = p.product_id)
LEFT JOIN oc_product_description pd ON (p.product_id = pd.product_id)
LEFT JOIN oc_product_to_store p2s ON (p.product_id = p2s.product_id)
WHERE pd.language_id = '1'
AND p.status = '1'
AND p.date_available <= NOW()
AND p2s.store_id = '0'
AND p2c.category_id = '76'
GROUP BY p.product_id
ORDER BY rating ASC, LCASE(pd.name) ASC
LIMIT 0,15
我需要先显示所有具有 的产品,position=1
然后再显示所有其他产品。我试图在最后添加ORDER BY position='1' DESC
,给出了一个错误。PS 请告诉我,我在哪里犯了错误(在 mysql 中,不幸的是,我理解马马虎虎)
你好!我想知道帖子类别 ID。知道帖子的id,怎么办?PS 自定义类别,分类ad_cat
。
你好!我只想在网站上显示某个类别的帖子(使用类别 ID)。有这个代码:
$args = array(
'numberposts' => '100000',
'category' => 35,
'post_type' => 'ad_listing',
);
$posts = get_posts($args);
但由于某种原因,数组是$posts
空的。如果删除'category' => 35
它,它会正常显示所有帖子
你好!该网站有一个下拉列表:
<ul class="dropdown-menu">
<li>Один</li>
<li>Два</li>
<li>Три</li>
</ul>
li
选择任何值(即在操作期间)时,如何使用 jquery 获取值(例如 data-... change
)?
你好!有这样的行:
/city/ufa/val1/
/city/kazan/val2/val3/
有必要从字符串中取出最后一个单词,即 从倒数第二个/
到最后一个/
(例如:第一种情况是 'val1',第二种情况是 'val3')。如何实施?
你好!该网站有一个代码,用于从该用户的每个帖子的用户余额中删除单位(提取多少取决于帖子本身的速率):
foreach ($posts as $post) {
if (is_sticky($post->ID) == true)
{
$postAutorId = $post->post_author;
$postAutorId = $postAutorId[0]; //id автора поста
$rate = get_post_meta($post->ID, 'cp_sys_total_ad_cost');
$rate = intval($rate[0]); // ставка за данный пост
$balance = get_user_meta($postAutorId, 'balance');
$balance = intval($balance[0]); //баланс пользователя
if($balance == '')
{
$balance = 0;
}
if($balance >= $rate) //Если баланс больше или равно ставке, уменьшаем баланс на ставку
{
$balance = $balance - $rate;
$res = $wpdb->query(
" UPDATE `wp_usermeta` SET `meta_value` = '$balance' WHERE `meta_key`='billing_city' AND `wp_usermeta`.`user_id` = '$postAutorId';"
); //Перезаписываем баланс
echo '<pre>';
var_dump($balance);
echo '<pre>';
}
else
{
//закрываем пост
// $wpdb->query(
// "UPDATE `wp_posts` SET `post_status` = 'pending' WHERE `wp_posts`.`ID` = '$postAutorId';"
// );
}
}
}
问题是,如果一个作者有两个帖子,由于某种原因,只扣除最后一个帖子的余额(例如:余额是'100',第一个帖子是'50',第二个帖子是'45'。如结果,用户的余额将是“55”而不是“5”)
你好!我有一个二维数组:
array(7) {
[0]=>
array(4) {
[0]=>
int(529)
[1]=>
string(5) "40.00"
}
[1]=>
array(4) {
[0]=>
int(525)
[1]=>
string(5) "50.00"
...
}
[1]
有必要按键(即按元素 40.00、50.00)以相反的顺序对该数组进行排序。如何实施?
我在主题的根目录中创建了一个包含 php 文件的文件夹。当我尝试在这些文件中运行标准函数时(例如:)update_post_meta
,它返回 500 错误,并写入日志Call to undefined function update_post_meta() in ...
。也许您需要在某处包含您的 php 文件,以便您可以在其中调用标准 WP 函数?
你好!WP 在哪里以及如何组成所有帖子的数组(对数据库的查询在哪里)?这是显示所有帖子的代码:
<?php while (have_posts()) : the_post(); ?>
<?php appthemes_before_post(); ?>
<?php get_template_part('content', APP_POST_TYPE); ?>
<?php appthemes_after_post(); ?>
<?php endwhile; ?>
<?php appthemes_after_endwhile(); ?>
<?php else: ?>
<?php appthemes_loop_else(); ?>
<?php endif; ?>
我需要重做数据库查询以更改帖子输出的顺序
网站上有几个select
循环显示:
$(".selectOptions").change(function() {
var href = $(".selectOptions :selected").val();
console.log(href);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select size="6" class="color form-control ocf-target selected selectOptions" name="color">
<option class="ir_Все" value="http://.../index.php?route=product/category&path=59" id="v-cancel-1">Все</option>
<option class="ir_3597ae" value="" id="v-12" disabled="disabled">Синий</option>
<option class="ir_ffffff" value="http://.../index.php?route=product/category&path=59&filter_ocfilter=1:22" id="v-122">Белый</option>
</select>
<select size="6" class="color form-control ocf-target selected selectOptions" name="color">
<option class="ir_fbaf00" value="http://.../index.php?route=product/category&path=59&filter_ocfilter=1:3" id="v-13" selected="selected">Желтый</option>
<option class="ir_ff0000" value="" id="v-11" disabled="disabled">Красный</option>
</select> ...
选择字段时,需要获取该字段的值。但由于某种原因,它仅从 first 中获取值select
。
你好!该站点有几个使用循环显示的选择。每个选择都应在单击特定按钮时展开(使用 js 和 css)。到目前为止,只有打开所有选择,但不是单独打开。那些。最后应该是这样的,点击Цвет
一个所有颜色都掉的列表,其余的列表不显示。PS循环中的选择数量可以改变,即 并不总是等于三
$('body').on('click', '.bnt', function(event) {
event.preventDefault();
$('.dropdown').toggle();
})
$('body').on('click', '.dropdown', function(event) {
event.preventDefault();
$('.dropdown').toggle();
})
select {
overflow: hidden;
border: none;
text-transform: uppercase;
}
option {
line-height: 20px;
padding: .5rem 1rem;
position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="bnt">ЦВЕТ</div>
<div class="dropdown" style="display: none">
<select size="3" class="color" name="color">
<option value="grey" class="grey">белый</option>
<option value="yellow" class="yellow">желтый</option>
<option value="green" class="green">зеленый</option>
</select>
</div>
<div class="bnt">Форма</div>
<div class="dropdown" style="display: none">
<select size="3" class="color" name="color">
<option value="grey" class="grey">Шар</option>
<option value="yellow" class="yellow">Куб</option>
<option value="green" class="green">Конус</option>
</select>
</div>
<div class="bnt">Содержимое</div>
<div class="dropdown" style="display: none">
<select size="3" class="color" name="color">
<option value="grey" class="grey">Текст1</option>
<option value="yellow" class="yellow">Текст2</option>
<option value="green" class="green">Текст3</option>
</select>
</div>