小编who*_*boy的帖子

使用Laravel将两个模型组合成一个带有急切加载关系的分页查询

我有两个模型,我想合并到一个时间轴.我已经能够通过在mysql中创建一个规范化和联合表的视图来实现这一点.我为这个视图创建了一个模型NewsFeed.如果我不想要相关Comment模型,这很有效.通过覆盖getMorphClass模型上的方法,我已经接近了这一点.这允许我获取图片的相关注释,但不能获得帖子,因为在getMorphClass调用时模型没有任何数据.

我对如何解决这个问题的方法持开放态度,而不仅仅是我提出的方式,但我不想从数据库中提取比我更多的数据.

新闻源

    <?php

    namespace App\Users;

    use App\Pictures\Picture;
    use App\Social\Comments\CommentableTrait;
    use App\Posts\Post;
    use App\Users\User;
    use Illuminate\Database\Eloquent\Model;

    class UserFeed extends Model
    {
        use CommentableTrait;

        public function user()
        {
            return $this->belongsTo(User::class);
        }

        public function getMorphClass(){
            if ($this->type == 'post'){
                return Post::class;
            }
            return Picture::class;
        }
    }
Run Code Online (Sandbox Code Playgroud)

MySQL视图

CREATE VIEW 
   `user_feeds`
AS SELECT
   `posts`.`id` AS `id`,
   `posts`.`user_id` AS `user_id`,
   'post' AS `type`,
   NULL AS `name`,
   NULL AS `thumbnail`,
   `posts`.`body` AS `body`,
   `posts`.`updated_at` AS `updated_at`,
   `posts`.`created_at` …
Run Code Online (Sandbox Code Playgroud)

php mysql laravel laravel-5.1

18
推荐指数
1
解决办法
853
查看次数

如何在 vue 3 中重用可组合的 props

本质上,我想构建输入字段组件(textfeids、textarea、复选框等)。由于它们共享一些属性,即(id、名称等),因此我的方法是创建一个可组合项并定义通用的 prop 定义,然后在各个组件中使用它们。然而,它似乎确实有效。有没有办法可以在 vue 3 可组合方法中实现这一目标。下面是可组合的。

// prop definition
import { defineProps } from "vue";

export const useCoreFieldProps = () => {
  const props = defineProps<{
    id?: string;
    name?: string;
    disabled?: boolean;
    required?: boolean;
  }>();

  return {
    props,
  };
};
Run Code Online (Sandbox Code Playgroud)
// composable usage
<script setup lang="ts">
import { useCoreFieldProps } from "@/composables/useFields";

const { props: coreProps } = useCoreFieldProps();

</script>
Run Code Online (Sandbox Code Playgroud)

vuejs3

17
推荐指数
1
解决办法
4298
查看次数

限制与Laravel的多态多对多关系中的相关记录

我正在使用Laravel 5.1,我需要使用多态多对多关系来限制我提取的相关记录的数量.

我想做的是通过parent_id获取类别列表.对于每个类别,我只想拉四个帖子.

我有这个使用下面的代码,但它导致一堆额外的查询.如果可能,我想只打一次数据库.如果可能的话,我想使用Laravel/Eloquent框架,但我愿意接受这方面的任何工作.

@foreach ($categories as $category)
  @if ($category->posts->count() > 0)
    <h2>{{ $category->name }}</h2>
    <a href="/style/{{ $category->slug }}">See more</a>

    {-- This part is the wonky part --}

    @foreach ($category->posts()->take(4)->get() as $post)

      {{ $post->body }}

    @endforeach

  @endif
@endforeach
Run Code Online (Sandbox Code Playgroud)

PostsController

public function index(Category $category)
{
  $categories = $category->with('posts')
      ->whereParentId(2)
      ->get();

  return view('posts.index')->with(compact('categories'));
}
Run Code Online (Sandbox Code Playgroud)

数据库

posts
    id - integer
    body - string

categories
    id - integer
    name - string
    parent_id - integer

categorizables
    category_id - integer
    categorizable_id - integer
    categorizable_type …
Run Code Online (Sandbox Code Playgroud)

php mysql laravel eloquent laravel-5

15
推荐指数
1
解决办法
2305
查看次数

在可组合项 vue3 中使用 props

我正在将应用程序从 vue 2 升级到 vue 3,但在可组合项方面遇到了一些问题。我想在可组合项中使用道具,但它似乎不起作用。代码示例是从工作组件中提取的,当我将其留在组件中时,它可以正常工作。

我认为defineProps可组合项不支持,但我不清楚如何处理它。当我传递src参数时,它会失去反应性。

// loadImage.js
import { defineProps, onMounted, ref, watch } from 'vue'

// by convention, composable function names start with "use"
export function useLoadImage() {
  let loadingImage = ref(true)
  let showImage = ref(false)
  const props = defineProps({
    src: String,
  })
  const delayShowImage = () => {
    setTimeout(() => {
      showImage.value = true
    }, 100)
  }
  const loadImage = (src) => {
    let img = new Image()
    img.onload = (e) => …
Run Code Online (Sandbox Code Playgroud)

vue.js vuejs3 vue-composition-api vue-script-setup

11
推荐指数
2
解决办法
1万
查看次数

使用Newtonsoft.Json解析JSON的错误

当我尝试使用Newtonsoft.Json解析我的JSON时,我收到以下错误

Response result = JsonConvert.DeserializeObject<Response>(unfilteredJSONData);
Run Code Online (Sandbox Code Playgroud)

无法将属性字符串添加到Newtonsoft.Json.Linq.JObject.对象上已存在具有相同名称的属性.

我无法控制JSON提要,他们只是添加了flags1flags2.重复的字符串似乎导致错误,但我对如何解决它没有任何好主意.在添加新字段之前,此代码运行良好.

更新:


第一个错误是由使用过时版本的JSON.net引起的.我使用的CMS系统有一个内置版本,它是3.5.当我使用4.5时,我收到一个新错误:

无法将Newtonsoft.Json.Linq.JValue添加到Newtonsoft.Json.Linq.JObject.

事实证明我的JSON与我正在处理的格式不完全相同.请注意更新.错误似乎是由此引起的:

"flags1": {
    "string": "text",
    "string": "text"
},
Run Code Online (Sandbox Code Playgroud)

JSON是:

{
    "result":
    {
        "lookups":
        [
            {
                "groups":
                [
                    {
                        "item0": "text",
                        "item1": "text",
                        "item2": 0,
                        "item3": 0,
                        "item4": 11.5,
                        "item5": true
                    },
                    {
                        "item6": "text",
                        "oddName": "text"
                    },
                    {
                        "item7": {
                            "subitem0": "text",
                            "subitem1": 0,
                            "subitem2": true
                        },
                        "item8": {
                            "subitem0": "string",
                            "subitem1": 0,
                            "subitem2": true
                        }
                    },
                    {
                        "url": "http://google.com",
                        "otherurl": "http://yahoo.com",
                        "alturllist": [],
                        "altotherurl": [] …
Run Code Online (Sandbox Code Playgroud)

.net c# linq json json.net

10
推荐指数
1
解决办法
3万
查看次数

PHP和Laravel的特征

我正在使用Laravel 5.1,并且当模型使用appends数组之前的Model时,想要从Trait访问Model上的数组.

如果它存在于我的特征中,我想将某些项添加到appends数组中.我不想编辑模型来实现这一目标.特征是在这种情况下实际可用还是应该使用继承?

array_push($this->appends, 'saucedByCurrentUser');
Run Code Online (Sandbox Code Playgroud)

以下是我当前设置的工作原理.

特征

<?php namespace App;

trait AwesomeSauceTrait {

  /**
   * Collection of the sauce on this record
   */
  public function awesomeSauced()
  {
    return $this->morphMany('App\AwesomeSauce', 'sauceable')->latest();
  }
  public function getSaucedByCurrentUserAttribute()
  {
    if(\Auth::guest()){
        return false;
    }
    $i = $this->awesomeSauced()->whereUserId(\Auth::user()->id)->count();
    if ($i > 0){
        return true;
    }
    return false;
  }
}
Run Code Online (Sandbox Code Playgroud)

模型

<?php namespace App;

use App\AwesomeSauceTrait;
use Illuminate\Database\Eloquent\Model;

class FairlyBlandModel extends Model {
    use AwesomeSauceTrait;

    protected $appends = array('age','saucedByCurrentUser');

}
Run Code Online (Sandbox Code Playgroud)

我想做的是达到与扩展课程相同的效果.我有一些类似的特征,所以使用继承有点难看.

trait AwesomeSauceTrait {
 function …
Run Code Online (Sandbox Code Playgroud)

php traits laravel laravel-5

10
推荐指数
1
解决办法
1万
查看次数

我正在使用Laravel 5的Command Bus,我不清楚如何实现验证器类

我正在使用Laravel 5的Command Bus,我不清楚如何实现验证器类.

我想创建一个ResizeImageCommandValidator类,在尝试调整图像大小之前检查图像实际上是图像.

我想提取的代码来自ResizeImageCommandHandler resize方法.

if (!($image instanceof Image))
{
    throw new ImageInvalidException('ResizeImageCommandHandler');
}
Run Code Online (Sandbox Code Playgroud)

这个想法来自Laracasts 命令和域事件,但Jeffrey没有使用Laravel 5架构.

这是代码.

ResizeImageCommandHandler.php

<?php namespace App\Handlers\Commands;

use App\Commands\ResizeImageCommand;

use App\Exceptions\ImageInvalidException;
use Illuminate\Queue\InteractsWithQueue;
use Intervention\Image\Image;

class ResizeImageCommandHandler {

    /**
     * Create the command handler.
     */
    public function __construct()
    {
    }
    /**
     * Handle the command.
     *
     * @param  ResizeImageCommand  $command
     * @return void
     */
    public function handle($command)
    {
        $this->resizeImage($command->image, $command->dimension);
    }
    /**
     * Resize the image by width, designed for square …
Run Code Online (Sandbox Code Playgroud)

php validation laravel laravel-5 laravel-validation

9
推荐指数
1
解决办法
2094
查看次数

使用 PHPUNIT 列出所有跳过的测试

我已经搜索并阅读了文档,或者至少我认为我已经阅读过,但是我一直无法找到是否有办法使用 PHPUNIT 获取所有跳过的测试的列表?

这可能吗?

php phpunit

8
推荐指数
1
解决办法
1617
查看次数

Laravel Phpunit和Dusk with CircleCI

有没有人能够让Laravel DuskCircleCI上工作.

我可以让我的构建工作并使用PHPUnit进行测试但是Laravel Dusk失败了.

我有一个安装了Dusk的Laravel基础安装.当我到达php artisan dusk命令时,我收到以下错误.

错误

1) Tests\Browser\ExampleTest::testBasicExample
Did not see expected text [Laravel] within element [body].
Failed asserting that false is true.
Run Code Online (Sandbox Code Playgroud)

所以它正在启动chromebrowser,但没有访问该网站.

我尝试使用Dusk的chromedriver-linux,circleci的chromedriver,不使用php服务和其他各种调整.到目前为止,我没有运气.

这是repo的链接,相关文件发布在下面.

这是我的circle.yml档案.

machine:
  hosts:
    dusk.dev: 127.0.0.1
  timezone: America/Los_Angeles
  services:
    - mysql
  environment:
      APP_ENV: testing
      APP_KEY: randomq2VjceHV2t1Usdskeksa9yUI6a
  post:
    - chromedriver:
        background: true
dependencies:
  override:
    - composer install --prefer-dist --no-interaction
  post:
    - mv .env.example .env

test:
  override:
    - vendor/bin/phpunit
#    - ./vendor/laravel/dusk/bin/chromedriver-linux:
#          background: true …
Run Code Online (Sandbox Code Playgroud)

php laravel circleci laravel-5 laravel-dusk

8
推荐指数
1
解决办法
869
查看次数

Laravel的文件系统,s3使用了错误的URL

我正在使用Laravel的文件系统在s3上存储项目,我得到了错误的URL.

Storage::disk('s3')->put('file.txt', 'Contents');
Run Code Online (Sandbox Code Playgroud)

给我错误

CurlException in CurlMulti.php line 359:
[curl] 6: Could not resolve host: mybucket.s3.website-us-east-1.amazonaws.com [url] https://mybucket.s3.website-us-east-1.amazonaws.com/file.txt
Run Code Online (Sandbox Code Playgroud)

这个URL

mybucket.s3.website-us-east-1.amazonaws.com

应该

mybucket.s3-website-us-east-1.amazonaws.com

配置/ filesystem.php

's3' => [
    'driver' => 's3',
    'key'    => env('S3_KEY'),
    'secret' => env('S3_SECRET'),
    'region' => env('S3_REGION'),
    'bucket' => env('S3_BUCKET'),
],
Run Code Online (Sandbox Code Playgroud)

.ENV

S3_KEY=MYKEY
S3_SECRET=mySecr3tmySecr3tmySecr3tmySecr3t
S3_REGION=website-us-east-1
S3_BUCKET=mybucket
Run Code Online (Sandbox Code Playgroud)

amazon-s3 laravel laravel-5 flysystem

7
推荐指数
1
解决办法
9040
查看次数