【问题标题】:Add attributes to laravel post为 laravel 帖子添加属性
【发布时间】:2017-10-16 00:36:40
【问题描述】:

我正在开发 laravel 电子商务项目,我需要在我的帖子中添加属性(下图为例)

我的问题是如何做到这一点?我应该创建新表还是可以像任何其他电子商务 cms 一样从 post.create 手动添加?

我个人更喜欢能够像我一样在post.create 中添加字段 添加+ 按钮,每次单击它时添加2个输入字段,然后我 可以把key和value放进去。 (如果你能帮助我)

谢谢。

更新:

在@anas-red 的建议下,我现在创建了这个结构:

attributes 表。

Schema::create('attributes', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title')->unique();
            $table->timestamps();
        });

product_attributes

Schema::create('product_attributes', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('product_id')->unsigned();
            $table->foreign('product_id')->references('id')->on('products');
            $table->integer('attribute_id')->unsigned();
            $table->foreign('attribute_id')->references('id')->on('attributes');
            $table->string('attribute_value')->nullable();
            $table->timestamps();
        });

现在当我保存帖子时,我的控制器上有这个存储方法:

public function store(Request $request)
    {
      //Validating title and body field
      $this->validate($request, array(
          'title'=>'required|max:225',
          'slug' =>'required|max:255',
          'user_id' =>'required|numeric',
          'image_one' =>'nullable|image',
          'image_two' =>'nullable|image',
          'image_three' =>'nullable|image',
          'image_four' =>'nullable|image',
          'image_one' =>'nullable|image',
          'short_description' => 'nullable|max:1000',
          'description' => 'nullable|max:100000',
          'subcategory_id' => 'required|numeric',
          'discount' => 'nullable|numeric',
          'discount_date' => 'nullable|date',
          'price' => 'required|numeric',
        ));

      $product = new Product;

      $product->title = $request->input('title');
      $product->slug = $request->input('slug');
      $product->user_id = $request->input('user_id');
      $product->description = $request->input('description');
      $product->short_description = $request->input('short_description');
      $product->subcategory_id = $request->input('subcategory_id');
      $product->discount = $request->input('discount');
      $product->discount_date = $request->input('discount_date');
      $product->price = $request->input('price');



      if ($request->hasFile('image')) {
        $image = $request->file('image');
        $filename = 'product' . '-' . time() . '.' . $image->getClientOriginalExtension();
        $location = public_path('images/');
        $request->file('image')->move($location, $filename);

        $product->image = $filename;
      }


      $product->save();

      $product->attributes()->sync($request->attributes, false);

      //Display a successful message upon save
      Session::flash('flash_message', 'Product, '. $product->title.' created');
      return redirect()->route('admin.products.index');
    }

我想做的过程是这样的:

  1. 存储我的属性
  2. 在创建新帖子时选择我的属性
  3. 为选定的属性赋值
  4. post_idarribute_idatteribute_value保存在product_attributes表中。

这是我得到的错误:

SQLSTATE[42S22]:找不到列:1054 未知列 'attributes_id' 在“字段列表”中(SQL:从product_attributes 中选择attributes_id 其中product_id = 29)

更新:

Product型号

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use jpmurray\LaravelCountdown\Traits\CalculateTimeDiff;

class Product extends Model
{
    use CalculateTimeDiff;

  protected $table = 'products';

  protected $fillable = [
      'title', 'slug', 'image_one', 'image_two', 'image_three', 'image_four', 'short_description', 'description', 'price', 'discount', 'discount_date',
  ];

  public function category(){
     return $this->belongsTo(Category::class);
  }
  public function subcategory(){
     return $this->belongsTo(Subcategory::class);
  }

  public function attributes()
  {
     return $this->belongsToMany(Attribute::class, 'product_attributes', 'product_id', 'attribute_id');
  }

  public function order(){
     return $this->hasMany(Order::class);
  }

  public function discounts(){
    return $this->hasMany(Discount::class, 'product_id', 'id');
  }


}

Attribute型号

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Attribute extends Model
{
  protected $fillable = [
      'title',
  ];

  public function products(){
     return $this->belongsToMany(Product::class);
  }
}

【问题讨论】:

标签: php jquery laravel


【解决方案1】:

我认为您可以添加新表让我们说“post_attributes”与以下列:

id - post_id - key - value

在 PostAttribute 模型中添加:

public function post
{
   return $this->belongsTo(Post::class); 
}

在 Post 模型中添加以下内容:

public function attributes 
{
   return $this->hasMany(PostAttributes::class, 'post_attributes'); 
}

现在该应用程序足够灵活,可以处理一个帖子的多个属性或另一个帖子的单个属性。

其他方法是在您的数据库中实现 JSON。希望对您有所帮助。

【讨论】:

  • 好吧,这似乎是对的,但你有我的第二个问题的解决方案吗? Personally I prefer to be able to add fields in post.create like I add + button and each time I click on it 2 input fields add and I can put key and value in it. (if you can help me with that)
  • 是的,您可以这样做。但是您必须使用 javascript 添加多个属性(键、值)。单击提交后,请求将转到您的控制器。然后在您的控制器中,您应该遍历所有这些并将它们保存到数据库。
  • 怎么回事?你觉得这有什么问题吗?有什么建议吗?
【解决方案2】:

更新产品模型

public function attributes()
{
    return $this->belongsToMany(Attribute::class, 'product_attributes', 'product_id', 'attribute_id')->withPivot('attribute_value')->withTimestamps();
}

并将属性模型更新为

public function products()
{
    return $this->belongsToMany(Product::class, 'product_attributes', 'attribute_id', 'product_id')->withPivot('attribute_value')->withTimestamps();
}

【讨论】:

  • 好的,兄弟现在保存整数但仍然无法保存值 imgur.com/a/Xiql5 PS 我发现在 laravel 中使用属性名称是不可接受的,因为使用消息发送邮件是不可接受的,所以我将我的属性更改为其他名称进行测试,我称之为more! :)
  • 是的,我对这个Attribute 的名字也有疑问。但是由于您没有提及任何错误,因此我跳过了它。
【解决方案3】:

如果我看到您的产品和属性模型,我将能够更好地正确回答您。

但无论如何,我认为您的问题在于product_attributes 表。 该表现在充当数据透视(中间)表,并且不遵循 Laravel 命名约定。约定将其命名如下:attribute_product

接下来,您必须将以下内容添加到两个模型中,即ProductAttribute

在属性模型中添加:

$this-&gt;belongsToMany(Product::class)-&gt;withPivot('value');

在产品型号中添加:

$this-&gt;belongsToMany(Attribute::class)-&gt;withPivot('value');

为数据透视表上的 more_value 列添加值。使用以下内容:

$product->attributes()->attach($attributeId, ['more_value' => $string]);

或使用同步:

$product->attributes()->sync([$attributeId => ['more_value' => $string]]);

【讨论】:

    【解决方案4】:

    哈哈。重要的部分是回购代码是:

    <input type="hidden" id="appOrderItems" name="orderItems[]">
    

    在我的 JS 部分跟踪 appOrderItems,你会得到它。

    简单来说:

    当用户将属性添加到产品(在我的例子中,项目到订单)然后,appOrderItems 数组将获取属性的 id 以及您需要添加到数据透视表中的任何附加值(除了product_id 和 attribute_id。在你的情况下是 mores_value)。在将这些属性收集到 appOrderItems JS 数组中后,我将其值推送到隐藏的 HTML 字段 (name="orderItems[]")。在这种情况下,它将被发送到控制器进行进一步处理。

    【讨论】:

    • 好的,现在我如何使用你的编码版本?在我看来,我不需要很多部分,可能在 js 中也是如此。
    • 您必须与 JS 打交道才能获得一个包含您的 attribute_id 和 mores_value 的数组,例如 arrayOfAttributes = ['id' => 1, 'more_value' => 'attribute value 1'] 等等。我不能只提供更多信息。你必须能够阅读别人的代码,分析,理解它,然后在你的代码中实现你自己的方式。阅读我的,如果您不理解任何代码,请回复我。
    • 你好兄弟,我在这里尝试另一种方式,你介意看看吗? stackoverflow.com/questions/46882735/…
    猜你喜欢
    • 2020-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-07
    • 2021-08-20
    相关资源
    最近更新 更多