Laravel 中的关系以及如何在 blade 中显示

Relations in Laravel and How to show it in blade

我正在寻找构建发票系统的简单方法我考虑 Laravel 因为我知道一点 PHP 和 MySQL。 我无法理解如何在表之间创建关系并显示它。 例如: 我有桌子:

用户 -ID -用户名 ...

客户端 -ID -名称 -地址 ...

产品 -ID -名称 -价格 ...

发票 -ID -client_id -> 前景 -user_id -> 前景 -数字 -product_id -> 前景

如何连接Laravel

用户有一些客户,这个客户有产品发票

并显示在发票列表中,用户可以为客户添加新发票等...

此致, 安德鲁

NOTE : The following example is just for the sake of demonsteration

首先你需要在你的模型中建立关系类型

例如:(一对多关系)Users & Products 表,一个用户可以购买很多产品并且购买的产品属于仅限每位用户。

所以它是一个许多

在您的User.php模型中您需要添加

public function products(){
    return $this->hasMany('App\Models\Product');
}

在您的Product.php模型中您需要添加

public function user(){
    return $this->belongsTo('App\Models\Product');
}

在获取用户时,您可以通过以下查询获取与该用户相关的产品

/* products inside with is the name of the function given in model */
$usersDetails = Models\User::with('products')->get();

现在用户将在查询

中拥有 产品 的密钥

现在在 blade 中,您可以通过以下方式访问产品

@foreach($users as $user)
    {{ $user->firstname }} - {{ $user->lastname }}

    @foreach($user->product as $product)
        {{ $product->name }}
    @endforeach
@endforeach

从迁移命令开始

php artisan make:migration CreateProductsTable

在这里定义你的结构,所以它看起来像这样:

Schema::create('products', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('sku')->unique();
        $table->double('price');
        $table->timestamps();
    });

之后你需要创建一个模型:

php artisan make:model Product

这会在您的 "App" 文件夹中创建一个 Product.php 文件

    class Product
{

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'sku', 'price'
    ];

}

如果某个字段未在 $fillable 中定义,您将无法 post 该字段。

现在创建一个 ProductController

php artisan make:controller ProductController

这必须看起来像这样:

        class ProductController extends Controller
    {

        public function __construct()
        {
            //$this->middleware('auth');
        }

        public function index(Request $request) {
            $data = $request->all();

            $product= Product::create([
                'name' => $data['product_name'],
                'sku' => $data['product_sku'],
                'price' => $data['product_price'],
            ]);
        }
}

当然你可以在产品table中添加user_id这样的字段,所以设置不同table之间的关系。

return $this->belongsTo('App\Models\Product');

但我认为您必须在此处将产品替换为用户才能访问产品。